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

/*----------------------------------------------------------------------------*/
/**
  @defgroup recipe_muse_flat         Recipe muse_flat: Combine several separate flat images into one master flat file, trace slice locations, and locate dark pixels.
  @author Peter Weilbacher (based on Joris Gerssen's draft)
  
        This recipe combines several separate flat-field images into one master
        flat-field file and traces the location of the slices on the CCD.
        The master flat contains the combined pixel values of the raw flat
        exposures, with respect to the image combination method used, normalized
        to the mean flux.
        The trace table contains polynomials defining the location of the slices
        on the CCD.

        Processing trims the raw data and records the overscan statistics,
        subtracts the bias (taking account of the overscan, if --overscan is not
        "none"), and optionally, the dark from each raw input image, converts
        them from adu to count, scales them according to their exposure time,
        and combines the exposures using input parameters.

        To trace the position of the slices on the CCD, their edges are located
        using a threshold method. The edge detection is repeated at given
        intervals thereby tracing the central position (the mean of both edges)
        and width of each slit vertically across the CCD. Deviant positions of
        detections on CCD rows can be detected and excluded before fitting a
        polynomial to all positions measured for one slice. The polynomial
        parameters for each slice are saved in the output trace table.

        Finally, the area between the now known slice edges is searched for
        dark (and bright) pixels, using statistics in each row of the master
        flat.
      
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*----------------------------------------------------------------------------*
 *                         Static variables                                   *
 *----------------------------------------------------------------------------*/
static const char *muse_flat_help =
  "This recipe combines several separate flat-field images into one master flat-field file and traces the location of the slices on the CCD. The master flat contains the combined pixel values of the raw flat exposures, with respect to the image combination method used, normalized to the mean flux. The trace table contains polynomials defining the location of the slices on the CCD. Processing trims the raw data and records the overscan statistics, subtracts the bias (taking account of the overscan, if --overscan is not \"none\"), and optionally, the dark from each raw input image, converts them from adu to count, scales them according to their exposure time, and combines the exposures using input parameters. To trace the position of the slices on the CCD, their edges are located using a threshold method. The edge detection is repeated at given intervals thereby tracing the central position (the mean of both edges) and width of each slit vertically across the CCD. Deviant positions of detections on CCD rows can be detected and excluded before fitting a polynomial to all positions measured for one slice. The polynomial parameters for each slice are saved in the output trace table. Finally, the area between the now known slice edges is searched for dark (and bright) pixels, using statistics in each row of the master flat.";

static const char *muse_flat_help_esorex =
  "\n\nInput frames for raw frame tag \"FLAT\":\n"
  "\n Frame tag            Type Req #Fr Description"
  "\n -------------------- ---- --- --- ------------"
  "\n FLAT                 raw   Y  >=3 Raw flat"
  "\n MASTER_BIAS          calib Y    1 Master bias"
  "\n MASTER_DARK          calib .    1 Master dark"
  "\n BADPIX_TABLE         calib .      Known bad pixels"
  "\n\nProduct frames for raw frame tag \"FLAT\":\n"
  "\n Frame tag            Level    Description"
  "\n -------------------- -------- ------------"
  "\n MASTER_FLAT          final    Master flat"
  "\n TRACE_TABLE          final    Trace table"
  "\n TRACE_SAMPLES        final    Table containing all tracing sample points, if --samples=true";

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

  @remark The recipe config is used to check for the tags as well as to create
          the documentation of this plugin.
 */
/*----------------------------------------------------------------------------*/
static cpl_recipeconfig *
muse_flat_new_recipeconfig(void)
{
  cpl_recipeconfig *recipeconfig = cpl_recipeconfig_new();
      
  cpl_recipeconfig_set_tag(recipeconfig, "FLAT", 3, -1);
  cpl_recipeconfig_set_input(recipeconfig, "FLAT", "MASTER_BIAS", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "FLAT", "MASTER_DARK", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "FLAT", "BADPIX_TABLE", -1, -1);
  cpl_recipeconfig_set_output(recipeconfig, "FLAT", "MASTER_FLAT");
  cpl_recipeconfig_set_output(recipeconfig, "FLAT", "TRACE_TABLE");
  cpl_recipeconfig_set_output(recipeconfig, "FLAT", "TRACE_SAMPLES");
    
  return recipeconfig;
} /* muse_flat_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_flat_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, "MASTER_FLAT")) {
    muse_processing_prepare_property(aHeader, "ESO QC FLAT INPUT[0-9]+ MEDIAN",
                                     CPL_TYPE_FLOAT,
                                     "Median value of raw flat i in input list");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT INPUT[0-9]+ MEAN",
                                     CPL_TYPE_FLOAT,
                                     "Mean value of raw flat i in input list");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT INPUT[0-9]+ STDEV",
                                     CPL_TYPE_FLOAT,
                                     "Standard deviation of raw flat i in input list");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT INPUT[0-9]+ MIN",
                                     CPL_TYPE_FLOAT,
                                     "Minimum value of raw flat i in input list");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT INPUT[0-9]+ MAX",
                                     CPL_TYPE_FLOAT,
                                     "Maximum value of raw flat i in input list");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT INPUT[0-9]+ NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in raw flat i in input list");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT MASTER MEDIAN",
                                     CPL_TYPE_FLOAT,
                                     "Median value of the master flat before normalization");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT MASTER MEAN",
                                     CPL_TYPE_FLOAT,
                                     "Mean value of the master flat before normalization");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT MASTER STDEV",
                                     CPL_TYPE_FLOAT,
                                     "Standard deviation of the master flat before normalization");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT MASTER MIN",
                                     CPL_TYPE_FLOAT,
                                     "Minimum value of the master flat before normalization");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT MASTER MAX",
                                     CPL_TYPE_FLOAT,
                                     "Maximum value of the master flat before normalization");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT MASTER INTFLUX",
                                     CPL_TYPE_FLOAT,
                                     "Flux value, integrated over the whole master flat field before normalization");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT MASTER NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT MASTER SLICE[0-9]+ MEAN",
                                     CPL_TYPE_FLOAT,
                                     "Mean value around the vertical center of slice j before normalization");
    muse_processing_prepare_property(aHeader, "ESO QC FLAT MASTER SLICE[0-9]+ STDEV",
                                     CPL_TYPE_FLOAT,
                                     "Standard deviation around the vertical center of slice j before normalization");
  } else if (!strcmp(aFrametag, "TRACE_TABLE")) {
    muse_processing_prepare_property(aHeader, "ESO QC TRACE SLICE_L XPOS",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Location of midpoint of leftmost slice");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE SLICE_L TILT",
                                     CPL_TYPE_FLOAT,
                                     "[deg] Tilt of leftmost slice, measured as angle from vertical direction");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE SLICE_R XPOS",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Location of midpoint of rightmost slice");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE SLICE_R TILT",
                                     CPL_TYPE_FLOAT,
                                     "[deg] Tilt of rightmost slice, measured as angle from vertical direction");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE SLICE[0-9]+ MAXSLOPE",
                                     CPL_TYPE_FLOAT,
                                     "The maximum slope of the derived tracing functions of slice j within the CCD.");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE SLICE10 WIDTH",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Width of top left slice in the IFU (10 on CCD)");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE SLICE46 WIDTH",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Width of top right slice in the IFU (46 on CCD)");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE SLICE3 WIDTH",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Width of bottom left slice in the IFU (3 on CCD)");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE SLICE39 WIDTH",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Width of bottom right slice in the IFU (39 on CCD)");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE WIDTHS MEDIAN",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Median width of slices");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE WIDTHS MEAN",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Mean width of slices");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE WIDTHS STDEV",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Standard deviation of widths of slices");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE WIDTHS MIN",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Minimum width of slices");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE WIDTHS MAX",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Maximum width of slices");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE GAPS MEDIAN",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Median of gaps between slices");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE GAPS MEAN",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Mean of gaps between slices");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE GAPS STDEV",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Standard deviation of gaps between slices");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE GAPS MIN",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Minimum of gap between slices");
    muse_processing_prepare_property(aHeader, "ESO QC TRACE GAPS MAX",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Maximum gap between slices");
  } else if (!strcmp(aFrametag, "TRACE_SAMPLES")) {
  } else {
    cpl_msg_warning(__func__, "Frame tag %s is not defined", aFrametag);
    return CPL_ERROR_ILLEGAL_INPUT;
  }
  return CPL_ERROR_NONE;
} /* muse_flat_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_flat_get_frame_level(const char *aFrametag)
{
  if (!aFrametag) {
    return CPL_FRAME_LEVEL_NONE;
  }
  if (!strcmp(aFrametag, "MASTER_FLAT")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  if (!strcmp(aFrametag, "TRACE_TABLE")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  if (!strcmp(aFrametag, "TRACE_SAMPLES")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  return CPL_FRAME_LEVEL_NONE;
} /* muse_flat_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_flat_get_frame_mode(const char *aFrametag)
{
  if (!aFrametag) {
    return MUSE_FRAME_MODE_ALL;
  }
  if (!strcmp(aFrametag, "MASTER_FLAT")) {
    return MUSE_FRAME_MODE_MASTER;
  }
  if (!strcmp(aFrametag, "TRACE_TABLE")) {
    return MUSE_FRAME_MODE_MASTER;
  }
  if (!strcmp(aFrametag, "TRACE_SAMPLES")) {
    return MUSE_FRAME_MODE_MASTER;
  }
  return MUSE_FRAME_MODE_ALL;
} /* muse_flat_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_flat_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_flat_new_recipeconfig(),
                               muse_flat_prepare_header,
                               muse_flat_get_frame_level,
                               muse_flat_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_flat.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_flat",
                              (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_flat.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_flat",
                              (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_flat.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_flat",
                              (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_flat.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_flat",
                              (double)30.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "ovscsigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ovscsigma");

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

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

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --nlow: Number of minimum pixels to reject with minmax */
  p = cpl_parameter_new_value("muse.muse_flat.nlow",
                              CPL_TYPE_INT,
                             "Number of minimum pixels to reject with minmax",
                              "muse.muse_flat",
                              (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_flat.nhigh",
                              CPL_TYPE_INT,
                             "Number of maximum pixels to reject with minmax",
                              "muse.muse_flat",
                              (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_flat.nkeep",
                              CPL_TYPE_INT,
                             "Number of pixels to keep with minmax",
                              "muse.muse_flat",
                              (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_flat.lsigma",
                              CPL_TYPE_DOUBLE,
                             "Low sigma for pixel rejection with sigclip",
                              "muse.muse_flat",
                              (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_flat.hsigma",
                              CPL_TYPE_DOUBLE,
                             "High sigma for pixel rejection with sigclip",
                              "muse.muse_flat",
                              (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_flat.scale",
                              CPL_TYPE_BOOL,
                             "Scale the individual images to a common exposure time before combining them.",
                              "muse.muse_flat",
                              (int)TRUE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "scale");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "scale");
  if (!getenv("MUSE_EXPERT_USER")) {
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_CLI);
  }

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --normalize: Normalize the master flat to the average flux */
  p = cpl_parameter_new_value("muse.muse_flat.normalize",
                              CPL_TYPE_BOOL,
                             "Normalize the master flat to the average flux",
                              "muse.muse_flat",
                              (int)TRUE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "normalize");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "normalize");
  if (!getenv("MUSE_EXPERT_USER")) {
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_CLI);
  }

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --trace: Trace the position of the slices on the master flat */
  p = cpl_parameter_new_value("muse.muse_flat.trace",
                              CPL_TYPE_BOOL,
                             "Trace the position of the slices on the master flat",
                              "muse.muse_flat",
                              (int)TRUE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "trace");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "trace");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --nsum: Number of lines over which to average when tracing */
  p = cpl_parameter_new_value("muse.muse_flat.nsum",
                              CPL_TYPE_INT,
                             "Number of lines over which to average when tracing",
                              "muse.muse_flat",
                              (int)32);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "nsum");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "nsum");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --order: Order of polynomial fit to the trace */
  p = cpl_parameter_new_value("muse.muse_flat.order",
                              CPL_TYPE_INT,
                             "Order of polynomial fit to the trace",
                              "muse.muse_flat",
                              (int)5);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "order");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "order");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --edgefrac: Fractional change required to identify edge when tracing */
  p = cpl_parameter_new_value("muse.muse_flat.edgefrac",
                              CPL_TYPE_DOUBLE,
                             "Fractional change required to identify edge when tracing",
                              "muse.muse_flat",
                              (double)0.5);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "edgefrac");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "edgefrac");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --losigmabadpix: Low sigma to find dark pixels in the master flat */
  p = cpl_parameter_new_value("muse.muse_flat.losigmabadpix",
                              CPL_TYPE_DOUBLE,
                             "Low sigma to find dark pixels in the master flat",
                              "muse.muse_flat",
                              (double)5.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "losigmabadpix");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "losigmabadpix");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --hisigmabadpix: High sigma to find bright pixels in the master flat */
  p = cpl_parameter_new_value("muse.muse_flat.hisigmabadpix",
                              CPL_TYPE_DOUBLE,
                             "High sigma to find bright pixels in the master flat",
                              "muse.muse_flat",
                              (double)5.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "hisigmabadpix");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "hisigmabadpix");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --samples: Create a table containing all tracing sample points. */
  p = cpl_parameter_new_value("muse.muse_flat.samples",
                              CPL_TYPE_BOOL,
                             "Create a table containing all tracing sample points.",
                              "muse.muse_flat",
                              (int)FALSE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "samples");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "samples");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --merge: Merge output products from different IFUs into a common file. */
  p = cpl_parameter_new_value("muse.muse_flat.merge",
                              CPL_TYPE_BOOL,
                             "Merge output products from different IFUs into a common file.",
                              "muse.muse_flat",
                              (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_flat_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_flat_params_fill(muse_flat_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_flat.nifu");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nifu = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.overscan");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->overscan = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.ovscreject");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscreject = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.ovscsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.ovscignore");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscignore = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.combine");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->combine_s = cpl_parameter_get_string(p);
  aParams->combine =
    (!strcasecmp(aParams->combine_s, "average")) ? MUSE_FLAT_PARAM_COMBINE_AVERAGE :
    (!strcasecmp(aParams->combine_s, "median")) ? MUSE_FLAT_PARAM_COMBINE_MEDIAN :
    (!strcasecmp(aParams->combine_s, "minmax")) ? MUSE_FLAT_PARAM_COMBINE_MINMAX :
    (!strcasecmp(aParams->combine_s, "sigclip")) ? MUSE_FLAT_PARAM_COMBINE_SIGCLIP :
      MUSE_FLAT_PARAM_COMBINE_INVALID_VALUE;
  cpl_ensure_code(aParams->combine != MUSE_FLAT_PARAM_COMBINE_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.nlow");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nlow = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.nhigh");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nhigh = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.nkeep");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nkeep = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.lsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.hsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->hsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.scale");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->scale = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.normalize");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->normalize = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.trace");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->trace = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.nsum");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nsum = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.order");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->order = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.edgefrac");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->edgefrac = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.losigmabadpix");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->losigmabadpix = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.hisigmabadpix");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->hisigmabadpix = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.samples");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->samples = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_flat.merge");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->merge = cpl_parameter_get_bool(p);
    
  return 0;
} /* muse_flat_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_flat_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_flat_params_t params;
  muse_flat_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_flat",
                                                recipe);
    rc = muse_flat_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_flat",
                                                  recipe);
      muse_flat_params_t *pars = cpl_malloc(sizeof(muse_flat_params_t));
      memcpy(pars, &params, sizeof(muse_flat_params_t));
      pars->nifu = nifu;
      int *rci = rcs + (nifu - 1);
      *rci = muse_flat_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_flat",
                                                  recipe);
      rc = muse_flat_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_flat_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_flat_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_flat_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_flat_help,
                           muse_flat_help_esorex);
  } else {
    helptext = cpl_sprintf("%s", muse_flat_help);
  }

  /* Initialize the CPL plugin stuff for this module */
  cpl_plugin_init(plugin, CPL_PLUGIN_API, MUSE_BINARY_VERSION,
                  CPL_PLUGIN_TYPE_RECIPE,
                  "muse_flat",
                  "Combine several separate flat images into one master flat file, trace slice locations, and locate dark pixels.",
                  helptext,
                  "Peter Weilbacher (based on Joris Gerssen's draft)",
                  "usd-help@eso.org",
                  muse_get_license(),
                  muse_flat_create,
                  muse_flat_exec,
                  muse_flat_destroy);
  cpl_pluginlist_append(aList, plugin);
  cpl_free(helptext);

  return 0;
} /* cpl_plugin_get_info() */

/**@}*/