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

/*----------------------------------------------------------------------------*/
/**
  @defgroup recipe_muse_scibasic         Recipe muse_scibasic: Remove the instrumental signature from the data of each CCD and convert them from an image into a pixel table.
  @author Peter Weilbacher
  
        Processing handles each raw input image separately: it trims the raw
        data and records the overscan statistics, subtracts the bias (taking
        account of the overscan, if --overscan is not "none"), optionally
        detects cosmic rays (note that by default cosmic ray rejection is
        handled in the post processing recipes while the data is reformatted
        into a datacube, so that the default setting is cr="none" here),
        converts the images from adu to count, subtracts the dark, divides by
        the flat-field, and (optionally) propagates the integrated flux value
        from the twilight-sky cube.

        [For special cases, users can choose to combine all input files at the
        image level, so that the pixel table is only created once, for the
        combined data. This is not recommended for science data, where the
        combination should take place after correcting for atmospheric effects,
        before the creation of the final cube.]

        The reduced image is then saved (if --saveimage=true).

        The input calibrations geometry table, trace table, and wavelength
        calibration table are used to assign 3D coordinates to each CCD-based
        pixel, thereby creating a pixel table for each exposure.

        If --skylines contains one or more wavelengths for (bright and isolated)
        sky emission lines, these lines are used to correct the wavelength
        calibration using an offset.

        The data is then cut to a useful wavelength range (if --crop=true).

        If an ILLUM exposure was given as input, it is then used to correct the
        relative illumination between all slices of one IFU. For this, the data
        of each slice is multiplied by the normalized median flux of that slice
        in the ILLUM exposure.

        As last step, the data is divided by the normalized twilight cube (if
        given), using the 3D coordinate of each pixel in the pixel table to
        interpolate the twilight correction onto the data.

        This pre-reduced pixel table for each exposure is then saved to disk.
      
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*----------------------------------------------------------------------------*
 *                         Static variables                                   *
 *----------------------------------------------------------------------------*/
static const char *muse_scibasic_help =
  "Processing handles each raw input image separately: it trims the raw data and records the overscan statistics, subtracts the bias (taking account of the overscan, if --overscan is not &none&), optionally detects cosmic rays (note that by default cosmic ray rejection is handled in the post processing recipes while the data is reformatted into a datacube, so that the default setting is cr=&none& here), converts the images from adu to count, subtracts the dark, divides by the flat-field, and (optionally) propagates the integrated flux value from the twilight-sky cube. [For special cases, users can choose to combine all input files at the image level, so that the pixel table is only created once, for the combined data. This is not recommended for science data, where the combination should take place after correcting for atmospheric effects, before the creation of the final cube.] The reduced image is then saved (if --saveimage=true). The input calibrations geometry table, trace table, and wavelength calibration table are used to assign 3D coordinates to each CCD-based pixel, thereby creating a pixel table for each exposure. If --skylines contains one or more wavelengths for (bright and isolated) sky emission lines, these lines are used to correct the wavelength calibration using an offset. The data is then cut to a useful wavelength range (if --crop=true). If an ILLUM exposure was given as input, it is then used to correct the relative illumination between all slices of one IFU. For this, the data of each slice is multiplied by the normalized median flux of that slice in the ILLUM exposure. As last step, the data is divided by the normalized twilight cube (if given), using the 3D coordinate of each pixel in the pixel table to interpolate the twilight correction onto the data. This pre-reduced pixel table for each exposure is then saved to disk.";

static const char *muse_scibasic_help_esorex =
  "\n\nInput frames for raw frame tag \"OBJECT\":\n"
  "\n Frame tag            Type Req #Fr Description"
  "\n -------------------- ---- --- --- ------------"
  "\n OBJECT               raw   .      Raw exposure of a science target"
  "\n STD                  raw   .      Raw exposure of a standard star field"
  "\n SKY                  raw   .      Raw exposure of an (almost) empty sky field"
  "\n ASTROMETRY           raw   .      Raw exposure of an astrometric field"
  "\n ILLUM                raw   .    1 Single optional raw (attached/illumination) flat-field exposure"
  "\n MASTER_BIAS          calib Y    1 Master bias"
  "\n MASTER_DARK          calib .    1 Master dark"
  "\n MASTER_FLAT          calib Y    1 Master flat"
  "\n TRACE_TABLE          calib Y    1 Trace table"
  "\n WAVECAL_TABLE        calib Y    1 Wavelength calibration table"
  "\n GEOMETRY_TABLE       calib Y    1 Relative positions of the slices in the field of view"
  "\n TWILIGHT_CUBE        calib .      Smoothed cube of twilight sky"
  "\n BADPIX_TABLE         calib .    1 Known bad pixels"
  "\n\nProduct frames for raw frame tag \"OBJECT\":\n"
  "\n Frame tag            Level    Description"
  "\n -------------------- -------- ------------"
  "\n OBJECT_RED           intermed Pre-processed CCD-based images for OBJECT input (if --saveimage=true)"
  "\n OBJECT_RESAMPLED     intermed Resampled 2D image for OBJECT input (if --resample=true)"
  "\n PIXTABLE_OBJECT      intermed Output pixel table for OBJECT input"
  "\n STD_RED              intermed Pre-processed CCD-based images for STD input (if --saveimage=true)"
  "\n STD_RESAMPLED        intermed Resampled 2D image for STD input (if --resample=true)"
  "\n PIXTABLE_STD         intermed Output pixel table for STD input"
  "\n SKY_RED              intermed Pre-processed CCD-based images for SKY input (if --saveimage=true)"
  "\n SKY_RESAMPLED        intermed Resampled 2D image for SKY input (if --resample=true)"
  "\n PIXTABLE_SKY         intermed Output pixel table for SKY input"
  "\n ASTROMETRY_RED       intermed Pre-processed CCD-based images for ASTROMETRY input (if --saveimage=true)"
  "\n ASTROMETRY_RESAMPLED intermed Resampled 2D image for ASTROMETRY input (if --resample=true)"
  "\n PIXTABLE_ASTROMETRY  intermed Output pixel table for ASTROMETRY input"  "\n\nInput frames for raw frame tag \"REDUCED\":\n"
  "\n Frame tag            Type Req #Fr Description"
  "\n -------------------- ---- --- --- ------------"
  "\n REDUCED              raw   Y      Reduced CCD image"
  "\n TRACE_TABLE          calib Y    1 Trace table"
  "\n WAVECAL_TABLE        calib Y    1 Wavelength calibration table"
  "\n GEOMETRY_TABLE       calib Y    1 Relative positions of the slices in the field of view"
  "\n\nProduct frames for raw frame tag \"REDUCED\":\n"
  "\n Frame tag            Level    Description"
  "\n -------------------- -------- ------------"
  "\n REDUCED_RESAMPLED    intermed Resampled 2D image (if --resample=true)"
  "\n PIXTABLE_REDUCED     intermed Output pixel table";

/*----------------------------------------------------------------------------*/
/**
  @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_scibasic_new_recipeconfig(void)
{
  cpl_recipeconfig *recipeconfig = cpl_recipeconfig_new();
      
  cpl_recipeconfig_set_tag(recipeconfig, "OBJECT", -1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "OBJECT", "MASTER_BIAS", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "OBJECT", "MASTER_DARK", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "OBJECT", "MASTER_FLAT", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "OBJECT", "TRACE_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "OBJECT", "WAVECAL_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "OBJECT", "GEOMETRY_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "OBJECT", "TWILIGHT_CUBE", -1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "OBJECT", "BADPIX_TABLE", -1, 1);
  cpl_recipeconfig_set_output(recipeconfig, "OBJECT", "OBJECT_RED");
  cpl_recipeconfig_set_output(recipeconfig, "OBJECT", "OBJECT_RESAMPLED");
  cpl_recipeconfig_set_output(recipeconfig, "OBJECT", "PIXTABLE_OBJECT");
  cpl_recipeconfig_set_tag(recipeconfig, "STD", -1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "STD", "MASTER_BIAS", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "STD", "MASTER_DARK", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "STD", "MASTER_FLAT", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "STD", "TRACE_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "STD", "WAVECAL_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "STD", "GEOMETRY_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "STD", "TWILIGHT_CUBE", -1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "STD", "BADPIX_TABLE", -1, 1);
  cpl_recipeconfig_set_output(recipeconfig, "STD", "STD_RED");
  cpl_recipeconfig_set_output(recipeconfig, "STD", "STD_RESAMPLED");
  cpl_recipeconfig_set_output(recipeconfig, "STD", "PIXTABLE_STD");
  cpl_recipeconfig_set_tag(recipeconfig, "SKY", -1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "SKY", "MASTER_BIAS", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKY", "MASTER_DARK", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKY", "MASTER_FLAT", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKY", "TRACE_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKY", "WAVECAL_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKY", "GEOMETRY_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKY", "TWILIGHT_CUBE", -1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "SKY", "BADPIX_TABLE", -1, 1);
  cpl_recipeconfig_set_output(recipeconfig, "SKY", "SKY_RED");
  cpl_recipeconfig_set_output(recipeconfig, "SKY", "SKY_RESAMPLED");
  cpl_recipeconfig_set_output(recipeconfig, "SKY", "PIXTABLE_SKY");
  cpl_recipeconfig_set_tag(recipeconfig, "ASTROMETRY", -1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "ASTROMETRY", "MASTER_BIAS", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ASTROMETRY", "MASTER_DARK", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ASTROMETRY", "MASTER_FLAT", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ASTROMETRY", "TRACE_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ASTROMETRY", "WAVECAL_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ASTROMETRY", "GEOMETRY_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ASTROMETRY", "TWILIGHT_CUBE", -1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "ASTROMETRY", "BADPIX_TABLE", -1, 1);
  cpl_recipeconfig_set_output(recipeconfig, "ASTROMETRY", "ASTROMETRY_RED");
  cpl_recipeconfig_set_output(recipeconfig, "ASTROMETRY", "ASTROMETRY_RESAMPLED");
  cpl_recipeconfig_set_output(recipeconfig, "ASTROMETRY", "PIXTABLE_ASTROMETRY");
  cpl_recipeconfig_set_tag(recipeconfig, "ILLUM", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ILLUM", "MASTER_BIAS", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ILLUM", "MASTER_DARK", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ILLUM", "MASTER_FLAT", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ILLUM", "TRACE_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ILLUM", "WAVECAL_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ILLUM", "GEOMETRY_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ILLUM", "TWILIGHT_CUBE", -1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "ILLUM", "BADPIX_TABLE", -1, 1);
      
  cpl_recipeconfig_set_tag(recipeconfig, "REDUCED", 1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "REDUCED", "TRACE_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "REDUCED", "WAVECAL_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "REDUCED", "GEOMETRY_TABLE", 1, 1);
  cpl_recipeconfig_set_output(recipeconfig, "REDUCED", "REDUCED_RESAMPLED");
  cpl_recipeconfig_set_output(recipeconfig, "REDUCED", "PIXTABLE_REDUCED");
    
  return recipeconfig;
} /* muse_scibasic_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_scibasic_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, "OBJECT_RED")) {
    muse_processing_prepare_property(aHeader, "ESO QC SCIBASIC NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data");
  } else if (!strcmp(aFrametag, "OBJECT_RESAMPLED")) {
  } else if (!strcmp(aFrametag, "PIXTABLE_OBJECT")) {
    muse_processing_prepare_property(aHeader, "ESO QC SCIBASIC NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data");
    muse_processing_prepare_property(aHeader, "ESO QC SCIBASIC LAMBDA SHIFT",
                                     CPL_TYPE_FLOAT,
                                     "[Angstrom] Shift in wavelength applied to the data using sky emission line(s)");
  } else if (!strcmp(aFrametag, "STD_RED")) {
    muse_processing_prepare_property(aHeader, "ESO QC SCIBASIC NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data");
  } else if (!strcmp(aFrametag, "STD_RESAMPLED")) {
  } else if (!strcmp(aFrametag, "PIXTABLE_STD")) {
    muse_processing_prepare_property(aHeader, "ESO QC SCIBASIC NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data");
  } else if (!strcmp(aFrametag, "SKY_RED")) {
    muse_processing_prepare_property(aHeader, "ESO QC SCIBASIC NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data");
  } else if (!strcmp(aFrametag, "SKY_RESAMPLED")) {
  } else if (!strcmp(aFrametag, "PIXTABLE_SKY")) {
    muse_processing_prepare_property(aHeader, "ESO QC SCIBASIC NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data");
  } else if (!strcmp(aFrametag, "ASTROMETRY_RED")) {
    muse_processing_prepare_property(aHeader, "ESO QC SCIBASIC NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data");
  } else if (!strcmp(aFrametag, "ASTROMETRY_RESAMPLED")) {
  } else if (!strcmp(aFrametag, "PIXTABLE_ASTROMETRY")) {
    muse_processing_prepare_property(aHeader, "ESO QC SCIBASIC NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data");
  } else if (!strcmp(aFrametag, "REDUCED_RESAMPLED")) {
  } else if (!strcmp(aFrametag, "PIXTABLE_REDUCED")) {
  } else {
    cpl_msg_warning(__func__, "Frame tag %s is not defined", aFrametag);
    return CPL_ERROR_ILLEGAL_INPUT;
  }
  return CPL_ERROR_NONE;
} /* muse_scibasic_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_scibasic_get_frame_level(const char *aFrametag)
{
  if (!aFrametag) {
    return CPL_FRAME_LEVEL_NONE;
  }
  if (!strcmp(aFrametag, "OBJECT_RED")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "OBJECT_RESAMPLED")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "PIXTABLE_OBJECT")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "STD_RED")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "STD_RESAMPLED")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "PIXTABLE_STD")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "SKY_RED")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "SKY_RESAMPLED")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "PIXTABLE_SKY")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "ASTROMETRY_RED")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "ASTROMETRY_RESAMPLED")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "PIXTABLE_ASTROMETRY")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "REDUCED_RESAMPLED")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  if (!strcmp(aFrametag, "PIXTABLE_REDUCED")) {
    return CPL_FRAME_LEVEL_INTERMEDIATE;
  }
  return CPL_FRAME_LEVEL_NONE;
} /* muse_scibasic_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_scibasic_get_frame_mode(const char *aFrametag)
{
  if (!aFrametag) {
    return MUSE_FRAME_MODE_ALL;
  }
  if (!strcmp(aFrametag, "OBJECT_RED")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "OBJECT_RESAMPLED")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "PIXTABLE_OBJECT")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "STD_RED")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "STD_RESAMPLED")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "PIXTABLE_STD")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "SKY_RED")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "SKY_RESAMPLED")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "PIXTABLE_SKY")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "ASTROMETRY_RED")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "ASTROMETRY_RESAMPLED")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "PIXTABLE_ASTROMETRY")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "REDUCED_RESAMPLED")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "PIXTABLE_REDUCED")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  return MUSE_FRAME_MODE_ALL;
} /* muse_scibasic_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_scibasic_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_scibasic_new_recipeconfig(),
                               muse_scibasic_prepare_header,
                               muse_scibasic_get_frame_level,
                               muse_scibasic_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_scibasic.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_scibasic",
                              (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_scibasic.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_scibasic",
                              (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_scibasic.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_scibasic",
                              (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_scibasic.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_scibasic",
                              (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 region of the CCD that are ignored when computing statistics or fits. */
  p = cpl_parameter_new_value("muse.muse_scibasic.ovscignore",
                              CPL_TYPE_INT,
                             "The number of pixels of the overscan adjacent to the data region of the CCD that are ignored when computing statistics or fits.",
                              "muse.muse_scibasic",
                              (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);
     
  /* --crop: Automatically crop the output pixel tables in wavelength depending on the expected useful wavelength range of the observation mode used (4750-9350 Angstrom for nominal mode, 4600-9350 Angstrom for extended mode). */
  p = cpl_parameter_new_value("muse.muse_scibasic.crop",
                              CPL_TYPE_BOOL,
                             "Automatically crop the output pixel tables in wavelength depending on the expected useful wavelength range of the observation mode used (4750-9350 Angstrom for nominal mode, 4600-9350 Angstrom for extended mode).",
                              "muse.muse_scibasic",
                              (int)TRUE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "crop");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "crop");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --cr: Type of cosmic ray cleaning to use (for quick-look data processing). */
  p = cpl_parameter_new_enum("muse.muse_scibasic.cr",
                             CPL_TYPE_STRING,
                             "Type of cosmic ray cleaning to use (for quick-look data processing).",
                             "muse.muse_scibasic",
                             (const char *)"none",
                             2,
                             (const char *)"none",
                             (const char *)"dcr");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "cr");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "cr");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --xbox: Search box size in x. Only used if cr=dcr. */
  p = cpl_parameter_new_value("muse.muse_scibasic.xbox",
                              CPL_TYPE_INT,
                             "Search box size in x. Only used if cr=dcr.",
                              "muse.muse_scibasic",
                              (int)15);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "xbox");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "xbox");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --ybox: Search box size in y. Only used if cr=dcr. */
  p = cpl_parameter_new_value("muse.muse_scibasic.ybox",
                              CPL_TYPE_INT,
                             "Search box size in y. Only used if cr=dcr.",
                              "muse.muse_scibasic",
                              (int)40);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "ybox");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ybox");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --passes: Maximum number of cleaning passes. Only used if cr=dcr. */
  p = cpl_parameter_new_value("muse.muse_scibasic.passes",
                              CPL_TYPE_INT,
                             "Maximum number of cleaning passes. Only used if cr=dcr.",
                              "muse.muse_scibasic",
                              (int)2);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "passes");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "passes");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --thres: Threshold for detection gap in factors of standard deviation. Only used if cr=dcr. */
  p = cpl_parameter_new_value("muse.muse_scibasic.thres",
                              CPL_TYPE_DOUBLE,
                             "Threshold for detection gap in factors of standard deviation. Only used if cr=dcr.",
                              "muse.muse_scibasic",
                              (double)5.8);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "thres");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "thres");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --combine: Type of combination to use. Note that in most cases, science exposures cannot easily be combined on the CCD level, so this should usually be kept as "none"! This does not pay attention about the type of input data, and will combine all raw inputs! */
  p = cpl_parameter_new_enum("muse.muse_scibasic.combine",
                             CPL_TYPE_STRING,
                             "Type of combination to use. Note that in most cases, science exposures cannot easily be combined on the CCD level, so this should usually be kept as \"none\"! This does not pay attention about the type of input data, and will combine all raw inputs!",
                             "muse.muse_scibasic",
                             (const char *)"none",
                             5,
                             (const char *)"none",
                             (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);
      
  /* --nlow: Number of minimum pixels to reject with minmax */
  p = cpl_parameter_new_value("muse.muse_scibasic.nlow",
                              CPL_TYPE_INT,
                             "Number of minimum pixels to reject with minmax",
                              "muse.muse_scibasic",
                              (int)1);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "nlow");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "nlow");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --nhigh: Number of maximum pixels to reject with minmax */
  p = cpl_parameter_new_value("muse.muse_scibasic.nhigh",
                              CPL_TYPE_INT,
                             "Number of maximum pixels to reject with minmax",
                              "muse.muse_scibasic",
                              (int)1);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "nhigh");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "nhigh");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --nkeep: Number of pixels to keep with minmax */
  p = cpl_parameter_new_value("muse.muse_scibasic.nkeep",
                              CPL_TYPE_INT,
                             "Number of pixels to keep with minmax",
                              "muse.muse_scibasic",
                              (int)1);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "nkeep");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "nkeep");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --lsigma: Low sigma for pixel rejection with sigclip */
  p = cpl_parameter_new_value("muse.muse_scibasic.lsigma",
                              CPL_TYPE_DOUBLE,
                             "Low sigma for pixel rejection with sigclip",
                              "muse.muse_scibasic",
                              (double)3);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "lsigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "lsigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --hsigma: High sigma for pixel rejection with sigclip */
  p = cpl_parameter_new_value("muse.muse_scibasic.hsigma",
                              CPL_TYPE_DOUBLE,
                             "High sigma for pixel rejection with sigclip",
                              "muse.muse_scibasic",
                              (double)3);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "hsigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "hsigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --scale: Scale the individual images to a common exposure time before combining them. */
  p = cpl_parameter_new_value("muse.muse_scibasic.scale",
                              CPL_TYPE_BOOL,
                             "Scale the individual images to a common exposure time before combining them.",
                              "muse.muse_scibasic",
                              (int)TRUE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "scale");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "scale");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --saveimage: Save the pre-processed CCD-based image of each input exposure before it is transformed into a pixel table. */
  p = cpl_parameter_new_value("muse.muse_scibasic.saveimage",
                              CPL_TYPE_BOOL,
                             "Save the pre-processed CCD-based image of each input exposure before it is transformed into a pixel table.",
                              "muse.muse_scibasic",
                              (int)TRUE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "saveimage");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "saveimage");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --skylines: List of wavelengths of sky emission lines (in Angstrom) to use as reference for wavelength offset correction using a Gaussian fit. It can contain multiple (isolated) lines, as comma-separated list, individual shifts are then combined into one weighted average offset. Set to "none" to deactivate. */
  p = cpl_parameter_new_value("muse.muse_scibasic.skylines",
                              CPL_TYPE_STRING,
                             "List of wavelengths of sky emission lines (in Angstrom) to use as reference for wavelength offset correction using a Gaussian fit. It can contain multiple (isolated) lines, as comma-separated list, individual shifts are then combined into one weighted average offset. Set to \"none\" to deactivate.",
                              "muse.muse_scibasic",
                              (const char *)"5577.339,6300.304");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "skylines");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "skylines");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --skyhalfwidth: Half-width of the extraction box (in Angstrom) around each sky emission line. */
  p = cpl_parameter_new_value("muse.muse_scibasic.skyhalfwidth",
                              CPL_TYPE_DOUBLE,
                             "Half-width of the extraction box (in Angstrom) around each sky emission line.",
                              "muse.muse_scibasic",
                              (double)5.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "skyhalfwidth");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "skyhalfwidth");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --skybinsize: Size of the bins (in Angstrom per pixel) for the intermediate spectrum to do the Gaussian fit to each sky emission line. */
  p = cpl_parameter_new_value("muse.muse_scibasic.skybinsize",
                              CPL_TYPE_DOUBLE,
                             "Size of the bins (in Angstrom per pixel) for the intermediate spectrum to do the Gaussian fit to each sky emission line.",
                              "muse.muse_scibasic",
                              (double)0.1);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "skybinsize");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "skybinsize");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --skyreject: Sigma clipping parameters for the intermediate spectrum to do the Gaussian fit to each sky emission line. Up to three comma-separated numbers can be given, which are interpreted as high sigma-clipping limit (float), low limit (float), and number of iterations (integer), respectively. */
  p = cpl_parameter_new_value("muse.muse_scibasic.skyreject",
                              CPL_TYPE_STRING,
                             "Sigma clipping parameters for the intermediate spectrum to do the Gaussian fit to each sky emission line. Up to three comma-separated numbers can be given, which are interpreted as high sigma-clipping limit (float), low limit (float), and number of iterations (integer), respectively.",
                              "muse.muse_scibasic",
                              (const char *)"15.,15.,1");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "skyreject");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "skyreject");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --resample: Resample the input science data into 2D spectral images using tracing and wavelength calibration solutions for a visual check. Note that the image produced will show small wiggles even when the input calibrations are good and were applied successfully! */
  p = cpl_parameter_new_value("muse.muse_scibasic.resample",
                              CPL_TYPE_BOOL,
                             "Resample the input science data into 2D spectral images using tracing and wavelength calibration solutions for a visual check. Note that the image produced will show small wiggles even when the input calibrations are good and were applied successfully!",
                              "muse.muse_scibasic",
                              (int)FALSE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "resample");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "resample");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --dlambda: Wavelength step (in Angstrom per pixel) to use for resampling. */
  p = cpl_parameter_new_value("muse.muse_scibasic.dlambda",
                              CPL_TYPE_DOUBLE,
                             "Wavelength step (in Angstrom per pixel) to use for resampling.",
                              "muse.muse_scibasic",
                              (double)1.25);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "dlambda");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "dlambda");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --merge: Merge output products from different IFUs into a common file. */
  p = cpl_parameter_new_value("muse.muse_scibasic.merge",
                              CPL_TYPE_BOOL,
                             "Merge output products from different IFUs into a common file.",
                              "muse.muse_scibasic",
                              (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_scibasic_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_scibasic_params_fill(muse_scibasic_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_scibasic.nifu");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nifu = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.overscan");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->overscan = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.ovscreject");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscreject = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.ovscsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.ovscignore");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscignore = cpl_parameter_get_int(p);
     
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.crop");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->crop = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.cr");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->cr_s = cpl_parameter_get_string(p);
  aParams->cr =
    (!strcasecmp(aParams->cr_s, "none")) ? MUSE_SCIBASIC_PARAM_CR_NONE :
    (!strcasecmp(aParams->cr_s, "dcr")) ? MUSE_SCIBASIC_PARAM_CR_DCR :
      MUSE_SCIBASIC_PARAM_CR_INVALID_VALUE;
  cpl_ensure_code(aParams->cr != MUSE_SCIBASIC_PARAM_CR_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.xbox");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->xbox = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.ybox");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ybox = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.passes");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->passes = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.thres");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->thres = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.combine");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->combine_s = cpl_parameter_get_string(p);
  aParams->combine =
    (!strcasecmp(aParams->combine_s, "none")) ? MUSE_SCIBASIC_PARAM_COMBINE_NONE :
    (!strcasecmp(aParams->combine_s, "average")) ? MUSE_SCIBASIC_PARAM_COMBINE_AVERAGE :
    (!strcasecmp(aParams->combine_s, "median")) ? MUSE_SCIBASIC_PARAM_COMBINE_MEDIAN :
    (!strcasecmp(aParams->combine_s, "minmax")) ? MUSE_SCIBASIC_PARAM_COMBINE_MINMAX :
    (!strcasecmp(aParams->combine_s, "sigclip")) ? MUSE_SCIBASIC_PARAM_COMBINE_SIGCLIP :
      MUSE_SCIBASIC_PARAM_COMBINE_INVALID_VALUE;
  cpl_ensure_code(aParams->combine != MUSE_SCIBASIC_PARAM_COMBINE_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.nlow");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nlow = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.nhigh");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nhigh = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.nkeep");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nkeep = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.lsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.hsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->hsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.scale");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->scale = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.saveimage");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->saveimage = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.skylines");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->skylines = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.skyhalfwidth");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->skyhalfwidth = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.skybinsize");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->skybinsize = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.skyreject");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->skyreject = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.resample");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->resample = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.dlambda");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->dlambda = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_scibasic.merge");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->merge = cpl_parameter_get_bool(p);
    
  return 0;
} /* muse_scibasic_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_scibasic_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_scibasic_params_t params;
  muse_scibasic_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_scibasic",
                                                recipe);
    rc = muse_scibasic_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_scibasic",
                                                  recipe);
      muse_scibasic_params_t *pars = cpl_malloc(sizeof(muse_scibasic_params_t));
      memcpy(pars, &params, sizeof(muse_scibasic_params_t));
      pars->nifu = nifu;
      int *rci = rcs + (nifu - 1);
      *rci = muse_scibasic_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_scibasic",
                                                  recipe);
      rc = muse_scibasic_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_scibasic_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_scibasic_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_scibasic_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_scibasic_help,
                           muse_scibasic_help_esorex);
  } else {
    helptext = cpl_sprintf("%s", muse_scibasic_help);
  }

  /* Initialize the CPL plugin stuff for this module */
  cpl_plugin_init(plugin, CPL_PLUGIN_API, MUSE_BINARY_VERSION,
                  CPL_PLUGIN_TYPE_RECIPE,
                  "muse_scibasic",
                  "Remove the instrumental signature from the data of each CCD and convert them from an image into a pixel table.",
                  helptext,
                  "Peter Weilbacher",
                  "usd-help@eso.org",
                  muse_get_license(),
                  muse_scibasic_create,
                  muse_scibasic_exec,
                  muse_scibasic_destroy);
  cpl_pluginlist_append(aList, plugin);
  cpl_free(helptext);

  return 0;
} /* cpl_plugin_get_info() */

/**@}*/