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

/*----------------------------------------------------------------------------*/
/**
  @defgroup recipe_muse_twilight         Recipe muse_twilight: Combine several twilight skyflats into one cube, compute correction factors for each IFU, and create a smooth 3D illumination correction.
  @author Peter Weilbacher
  
        Processing first 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"), converts the
        images from adu to count, subtracts the dark, divides by the flat-field
        and combines all the exposures using input parameters.

        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 from the master sky-flat. These
        pixel tables are then cut in wavelength using the --lambdamin and
        --lambdamax parameters. The integrated flux in each IFU is computed as
        the sum of the data in the pixel table, and saved in the header, to be
        used later as estimate for the relative throughput of each IFU.

        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 within the pixel table of each IFU is multiplied by the
        normalized median flux of that slice in the ILLUM exposure.

        The pixel tables of all IFUs are then merged, using the integrated
        fluxes as inverse scaling factors, and a cube is reconstructed from the
        merged dataset, using given parameters. A white-light image is created
        from the cube. This skyflat cube is then saved to disk, with the
        white-light image as one extension.

        To construct a smooth 3D illumination correction, the cube is
        post-processed in the following way: the white-light image is used to
        create a mask of the illuminated area. From this area, the optional
        vignetting mask is removed. The smoothing is then computed for each
        plane of the cube: the illuminated area is smoothed (by a 5x7 median
        filter), normalized, fit with a 2D polynomial (of given polynomial
        orders), and normalized again.
        A smooth white image is then created by collapsing the smooth cube.

        If a vignetting mask was given, the corner area given by the mask is
        used to compute a 2D correction for the vignetted area: the original
        unsmoothed white-light image is corrected for large scale gradients by
        dividing it with the smooth white image. The residuals in the corner
        area then smoothed using input parameters. This smoothed vignetting
        correction is the multiplied onto each plane of the smooth cube,
        normalizing each plane again.

        This twilight cube is then saved to disk.
      
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*----------------------------------------------------------------------------*
 *                         Static variables                                   *
 *----------------------------------------------------------------------------*/
static const char *muse_twilight_help =
  "Processing first 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&), converts the images from adu to count, subtracts the dark, divides by the flat-field and combines all the exposures using input parameters. 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 from the master sky-flat. These pixel tables are then cut in wavelength using the --lambdamin and --lambdamax parameters. The integrated flux in each IFU is computed as the sum of the data in the pixel table, and saved in the header, to be used later as estimate for the relative throughput of each IFU. 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 within the pixel table of each IFU is multiplied by the normalized median flux of that slice in the ILLUM exposure. The pixel tables of all IFUs are then merged, using the integrated fluxes as inverse scaling factors, and a cube is reconstructed from the merged dataset, using given parameters. A white-light image is created from the cube. This skyflat cube is then saved to disk, with the white-light image as one extension. To construct a smooth 3D illumination correction, the cube is post-processed in the following way: the white-light image is used to create a mask of the illuminated area. From this area, the optional vignetting mask is removed. The smoothing is then computed for each plane of the cube: the illuminated area is smoothed (by a 5x7 median filter), normalized, fit with a 2D polynomial (of given polynomial orders), and normalized again. A smooth white image is then created by collapsing the smooth cube. If a vignetting mask was given, the corner area given by the mask is used to compute a 2D correction for the vignetted area: the original unsmoothed white-light image is corrected for large scale gradients by dividing it with the smooth white image. The residuals in the corner area then smoothed using input parameters. This smoothed vignetting correction is the multiplied onto each plane of the smooth cube, normalizing each plane again. This twilight cube is then saved to disk.";

static const char *muse_twilight_help_esorex =
  "\n\nInput frames for raw frame tag \"SKYFLAT\":\n"
  "\n Frame tag            Type Req #Fr Description"
  "\n -------------------- ---- --- --- ------------"
  "\n SKYFLAT              raw   Y  >=3 Raw twilight skyflat"
  "\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 BADPIX_TABLE         calib .      Known bad pixels"
  "\n TRACE_TABLE          calib Y    1 Tracing table for all slices"
  "\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 VIGNETTING_MASK      calib .    1 Mask to mark vignetted regions in the MUSE field of view"
  "\n\nProduct frames for raw frame tag \"SKYFLAT\":\n"
  "\n Frame tag            Level    Description"
  "\n -------------------- -------- ------------"
  "\n DATACUBE_SKYFLAT     final    Cube of combined twilight skyflat exposures"
  "\n TWILIGHT_CUBE        final    Smoothed cube of twilight sky";

/*----------------------------------------------------------------------------*/
/**
  @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_twilight_new_recipeconfig(void)
{
  cpl_recipeconfig *recipeconfig = cpl_recipeconfig_new();
      
  cpl_recipeconfig_set_tag(recipeconfig, "SKYFLAT", 3, -1);
  cpl_recipeconfig_set_input(recipeconfig, "SKYFLAT", "MASTER_BIAS", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKYFLAT", "MASTER_DARK", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKYFLAT", "MASTER_FLAT", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKYFLAT", "BADPIX_TABLE", -1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "SKYFLAT", "TRACE_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKYFLAT", "WAVECAL_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKYFLAT", "GEOMETRY_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "SKYFLAT", "VIGNETTING_MASK", -1, 1);
  cpl_recipeconfig_set_output(recipeconfig, "SKYFLAT", "DATACUBE_SKYFLAT");
  cpl_recipeconfig_set_output(recipeconfig, "SKYFLAT", "TWILIGHT_CUBE");
  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", "BADPIX_TABLE", -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", "VIGNETTING_MASK", -1, 1);
    
  return recipeconfig;
} /* muse_twilight_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_twilight_prepare_header(const char *aFrametag, cpl_propertylist *aHeader)
{
  cpl_ensure_code(aFrametag, CPL_ERROR_NULL_INPUT);
  cpl_ensure_code(aHeader, CPL_ERROR_NULL_INPUT);
  if (!strcmp(aFrametag, "DATACUBE_SKYFLAT")) {
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ INPUT[0-9]+ MEDIAN",
                                     CPL_TYPE_FLOAT,
                                     "Median value of raw exposure i of IFU m in input list");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ INPUT[0-9]+ MEAN",
                                     CPL_TYPE_FLOAT,
                                     "Mean value of raw exposure i of IFU m in input list");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ INPUT[0-9]+ STDEV",
                                     CPL_TYPE_FLOAT,
                                     "Standard deviation of raw exposure i of IFU m in input list");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ INPUT[0-9]+ MIN",
                                     CPL_TYPE_FLOAT,
                                     "Minimum value of raw exposure i of IFU m in input list");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ INPUT[0-9]+ MAX",
                                     CPL_TYPE_FLOAT,
                                     "Maximum value of raw exposure i of IFU m in input list");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ INPUT[0-9]+ NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in raw exposure i of IFU m in input list");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ MASTER MEDIAN",
                                     CPL_TYPE_FLOAT,
                                     "Median value of the combined exposures in IFU m");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ MASTER MEAN",
                                     CPL_TYPE_FLOAT,
                                     "Mean value of the combined exposures in IFU m");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ MASTER STDEV",
                                     CPL_TYPE_FLOAT,
                                     "Standard deviation of the combined exposures in IFU m");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ MASTER MIN",
                                     CPL_TYPE_FLOAT,
                                     "Minimum value of the combined exposures in IFU m");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ MASTER MAX",
                                     CPL_TYPE_FLOAT,
                                     "Maximum value of the combined exposures in IFU m");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ MASTER INTFLUX",
                                     CPL_TYPE_FLOAT,
                                     "Flux integrated over the whole CCD of the combined exposures of IFU m");
    muse_processing_prepare_property(aHeader, "ESO QC TWILIGHT[0-9]+ INTFLUX",
                                     CPL_TYPE_FLOAT,
                                     "Flux integrated over all slices of IFU m. Computed using the pixel table of the exposure.");
  } else if (!strcmp(aFrametag, "TWILIGHT_CUBE")) {
  } else {
    cpl_msg_warning(__func__, "Frame tag %s is not defined", aFrametag);
    return CPL_ERROR_ILLEGAL_INPUT;
  }
  return CPL_ERROR_NONE;
} /* muse_twilight_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_twilight_get_frame_level(const char *aFrametag)
{
  if (!aFrametag) {
    return CPL_FRAME_LEVEL_NONE;
  }
  if (!strcmp(aFrametag, "DATACUBE_SKYFLAT")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  if (!strcmp(aFrametag, "TWILIGHT_CUBE")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  return CPL_FRAME_LEVEL_NONE;
} /* muse_twilight_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_twilight_get_frame_mode(const char *aFrametag)
{
  if (!aFrametag) {
    return MUSE_FRAME_MODE_ALL;
  }
  if (!strcmp(aFrametag, "DATACUBE_SKYFLAT")) {
    return MUSE_FRAME_MODE_MASTER;
  }
  if (!strcmp(aFrametag, "TWILIGHT_CUBE")) {
    return MUSE_FRAME_MODE_MASTER;
  }
  return MUSE_FRAME_MODE_ALL;
} /* muse_twilight_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_twilight_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_twilight_new_recipeconfig(),
                               muse_twilight_prepare_header,
                               muse_twilight_get_frame_level,
                               muse_twilight_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;
      
  /* --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_twilight.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_twilight",
                              (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_twilight.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_twilight",
                              (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_twilight.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_twilight",
                              (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_twilight.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_twilight",
                              (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_twilight.combine",
                             CPL_TYPE_STRING,
                             "Type of combination to use",
                             "muse.muse_twilight",
                             (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_twilight.nlow",
                              CPL_TYPE_INT,
                             "Number of minimum pixels to reject with minmax",
                              "muse.muse_twilight",
                              (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_twilight.nhigh",
                              CPL_TYPE_INT,
                             "Number of maximum pixels to reject with minmax",
                              "muse.muse_twilight",
                              (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_twilight.nkeep",
                              CPL_TYPE_INT,
                             "Number of pixels to keep with minmax",
                              "muse.muse_twilight",
                              (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_twilight.lsigma",
                              CPL_TYPE_DOUBLE,
                             "Low sigma for pixel rejection with sigclip",
                              "muse.muse_twilight",
                              (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_twilight.hsigma",
                              CPL_TYPE_DOUBLE,
                             "High sigma for pixel rejection with sigclip",
                              "muse.muse_twilight",
                              (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_twilight.scale",
                              CPL_TYPE_BOOL,
                             "Scale the individual images to a common exposure time before combining them.",
                              "muse.muse_twilight",
                              (int)FALSE);
  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);
      
  /* --resample: The resampling technique to use for the final output cube. */
  p = cpl_parameter_new_enum("muse.muse_twilight.resample",
                             CPL_TYPE_STRING,
                             "The resampling technique to use for the final output cube.",
                             "muse.muse_twilight",
                             (const char *)"drizzle",
                             6,
                             (const char *)"nearest",
                             (const char *)"linear",
                             (const char *)"quadratic",
                             (const char *)"renka",
                             (const char *)"drizzle",
                             (const char *)"lanczos");
  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);
      
  /* --crtype: Type of statistics used for detection of cosmic rays during final resampling. "iraf" uses the variance information, "mean" uses standard (mean/stdev) statistics, "median" uses median and the median median of the absolute median deviation. */
  p = cpl_parameter_new_enum("muse.muse_twilight.crtype",
                             CPL_TYPE_STRING,
                             "Type of statistics used for detection of cosmic rays during final resampling. \"iraf\" uses the variance information, \"mean\" uses standard (mean/stdev) statistics, \"median\" uses median and the median median of the absolute median deviation.",
                             "muse.muse_twilight",
                             (const char *)"median",
                             3,
                             (const char *)"iraf",
                             (const char *)"mean",
                             (const char *)"median");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "crtype");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "crtype");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --crsigma: Sigma rejection factor to use for cosmic ray rejection during final resampling. A zero or negative value switches cosmic ray rejection off. */
  p = cpl_parameter_new_value("muse.muse_twilight.crsigma",
                              CPL_TYPE_DOUBLE,
                             "Sigma rejection factor to use for cosmic ray rejection during final resampling. A zero or negative value switches cosmic ray rejection off.",
                              "muse.muse_twilight",
                              (double)50.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "crsigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "crsigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --lambdamin: Minimum wavelength for twilight reconstruction. */
  p = cpl_parameter_new_value("muse.muse_twilight.lambdamin",
                              CPL_TYPE_DOUBLE,
                             "Minimum wavelength for twilight reconstruction.",
                              "muse.muse_twilight",
                              (double)5000.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "lambdamin");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "lambdamin");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --lambdamax: Maximum wavelength for twilight reconstruction. */
  p = cpl_parameter_new_value("muse.muse_twilight.lambdamax",
                              CPL_TYPE_DOUBLE,
                             "Maximum wavelength for twilight reconstruction.",
                              "muse.muse_twilight",
                              (double)9000.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "lambdamax");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "lambdamax");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --dlambda: Sampling for twilight reconstruction, this should result in planes of equal wavelength coverage. */
  p = cpl_parameter_new_value("muse.muse_twilight.dlambda",
                              CPL_TYPE_DOUBLE,
                             "Sampling for twilight reconstruction, this should result in planes of equal wavelength coverage.",
                              "muse.muse_twilight",
                              (double)250.);
  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);
      
  /* --xorder: Polynomial order to use in x direction to fit the full field of view. */
  p = cpl_parameter_new_value("muse.muse_twilight.xorder",
                              CPL_TYPE_INT,
                             "Polynomial order to use in x direction to fit the full field of view.",
                              "muse.muse_twilight",
                              (int)2);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "xorder");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "xorder");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --yorder: Polynomial order to use in y direction to fit the full field of view. */
  p = cpl_parameter_new_value("muse.muse_twilight.yorder",
                              CPL_TYPE_INT,
                             "Polynomial order to use in y direction to fit the full field of view.",
                              "muse.muse_twilight",
                              (int)2);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "yorder");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "yorder");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --vignmaskedges: Pixels on edges stronger than this fraction in the normalized image are excluded from the fit to the vignetted area. Set to non-positive number to include them in the fit. */
  p = cpl_parameter_new_value("muse.muse_twilight.vignmaskedges",
                              CPL_TYPE_DOUBLE,
                             "Pixels on edges stronger than this fraction in the normalized image are excluded from the fit to the vignetted area. Set to non-positive number to include them in the fit.",
                              "muse.muse_twilight",
                              (double)0.02);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "vignmaskedges");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "vignmaskedges");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --vignsmooth: Type of smoothing to use for the vignetted region given by the VIGNETTING_MASK; gaussian uses (vignxpar + vignypar)/2 as FWHM. */
  p = cpl_parameter_new_enum("muse.muse_twilight.vignsmooth",
                             CPL_TYPE_STRING,
                             "Type of smoothing to use for the vignetted region given by the VIGNETTING_MASK; gaussian uses (vignxpar + vignypar)/2 as FWHM.",
                             "muse.muse_twilight",
                             (const char *)"polyfit",
                             3,
                             (const char *)"polyfit",
                             (const char *)"gaussian",
                             (const char *)"median");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "vignsmooth");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "vignsmooth");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --vignxpar: Parameter used by the vignetting smoothing: x order for polyfit (default, recommended 4), parameter that influences the FWHM for the gaussian (recommended: 10), or x dimension of median filter (recommended 5). */
  p = cpl_parameter_new_value("muse.muse_twilight.vignxpar",
                              CPL_TYPE_INT,
                             "Parameter used by the vignetting smoothing: x order for polyfit (default, recommended 4), parameter that influences the FWHM for the gaussian (recommended: 10), or x dimension of median filter (recommended 5).",
                              "muse.muse_twilight",
                              (int)4);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "vignxpar");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "vignxpar");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --vignypar: Parameter used by the vignetting smoothing: y order for polyfit (default, recommended 4), parameter that influences the FWHM for the gaussian (recommended: 10), or y dimension of median filter (recommended 5). */
  p = cpl_parameter_new_value("muse.muse_twilight.vignypar",
                              CPL_TYPE_INT,
                             "Parameter used by the vignetting smoothing: y order for polyfit (default, recommended 4), parameter that influences the FWHM for the gaussian (recommended: 10), or y dimension of median filter (recommended 5).",
                              "muse.muse_twilight",
                              (int)4);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "vignypar");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "vignypar");

  cpl_parameterlist_append(recipe->parameters, p);
    
  return 0;
} /* muse_twilight_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_twilight_params_fill(muse_twilight_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_twilight.overscan");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->overscan = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.ovscreject");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscreject = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.ovscsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.ovscignore");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscignore = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.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_TWILIGHT_PARAM_COMBINE_AVERAGE :
    (!strcasecmp(aParams->combine_s, "median")) ? MUSE_TWILIGHT_PARAM_COMBINE_MEDIAN :
    (!strcasecmp(aParams->combine_s, "minmax")) ? MUSE_TWILIGHT_PARAM_COMBINE_MINMAX :
    (!strcasecmp(aParams->combine_s, "sigclip")) ? MUSE_TWILIGHT_PARAM_COMBINE_SIGCLIP :
      MUSE_TWILIGHT_PARAM_COMBINE_INVALID_VALUE;
  cpl_ensure_code(aParams->combine != MUSE_TWILIGHT_PARAM_COMBINE_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.nlow");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nlow = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.nhigh");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nhigh = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.nkeep");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nkeep = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.lsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.hsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->hsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.scale");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->scale = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.resample");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->resample_s = cpl_parameter_get_string(p);
  aParams->resample =
    (!strcasecmp(aParams->resample_s, "nearest")) ? MUSE_TWILIGHT_PARAM_RESAMPLE_NEAREST :
    (!strcasecmp(aParams->resample_s, "linear")) ? MUSE_TWILIGHT_PARAM_RESAMPLE_LINEAR :
    (!strcasecmp(aParams->resample_s, "quadratic")) ? MUSE_TWILIGHT_PARAM_RESAMPLE_QUADRATIC :
    (!strcasecmp(aParams->resample_s, "renka")) ? MUSE_TWILIGHT_PARAM_RESAMPLE_RENKA :
    (!strcasecmp(aParams->resample_s, "drizzle")) ? MUSE_TWILIGHT_PARAM_RESAMPLE_DRIZZLE :
    (!strcasecmp(aParams->resample_s, "lanczos")) ? MUSE_TWILIGHT_PARAM_RESAMPLE_LANCZOS :
      MUSE_TWILIGHT_PARAM_RESAMPLE_INVALID_VALUE;
  cpl_ensure_code(aParams->resample != MUSE_TWILIGHT_PARAM_RESAMPLE_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.crtype");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->crtype_s = cpl_parameter_get_string(p);
  aParams->crtype =
    (!strcasecmp(aParams->crtype_s, "iraf")) ? MUSE_TWILIGHT_PARAM_CRTYPE_IRAF :
    (!strcasecmp(aParams->crtype_s, "mean")) ? MUSE_TWILIGHT_PARAM_CRTYPE_MEAN :
    (!strcasecmp(aParams->crtype_s, "median")) ? MUSE_TWILIGHT_PARAM_CRTYPE_MEDIAN :
      MUSE_TWILIGHT_PARAM_CRTYPE_INVALID_VALUE;
  cpl_ensure_code(aParams->crtype != MUSE_TWILIGHT_PARAM_CRTYPE_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.crsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->crsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.lambdamin");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lambdamin = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.lambdamax");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lambdamax = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.dlambda");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->dlambda = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.xorder");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->xorder = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.yorder");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->yorder = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.vignmaskedges");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->vignmaskedges = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.vignsmooth");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->vignsmooth_s = cpl_parameter_get_string(p);
  aParams->vignsmooth =
    (!strcasecmp(aParams->vignsmooth_s, "polyfit")) ? MUSE_TWILIGHT_PARAM_VIGNSMOOTH_POLYFIT :
    (!strcasecmp(aParams->vignsmooth_s, "gaussian")) ? MUSE_TWILIGHT_PARAM_VIGNSMOOTH_GAUSSIAN :
    (!strcasecmp(aParams->vignsmooth_s, "median")) ? MUSE_TWILIGHT_PARAM_VIGNSMOOTH_MEDIAN :
      MUSE_TWILIGHT_PARAM_VIGNSMOOTH_INVALID_VALUE;
  cpl_ensure_code(aParams->vignsmooth != MUSE_TWILIGHT_PARAM_VIGNSMOOTH_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.vignxpar");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->vignxpar = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_twilight.vignypar");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->vignypar = cpl_parameter_get_int(p);
    
  return 0;
} /* muse_twilight_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_twilight_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_twilight_params_t params;
  muse_twilight_params_fill(&params, recipe->parameters);

  cpl_errorstate prestate = cpl_errorstate_get();

  muse_processing *proc = muse_processing_new("muse_twilight",
                                              recipe);
  int rc = muse_twilight_compute(proc, &params);
  cpl_frameset_join(usedframes, proc->usedframes);
  cpl_frameset_join(outframes, proc->outframes);
  muse_processing_delete(proc);
  
  if (!cpl_errorstate_is_equal(prestate)) {
    /* dump all errors from this recipe in chronological order */
    cpl_errorstate_dump(prestate, CPL_FALSE, muse_cplerrorstate_dump_some);
    /* reset message level to not get the same errors displayed again by esorex */
    cpl_msg_set_level(CPL_MSG_INFO);
  }
  /* clean up duplicates in framesets of used and output frames */
  muse_cplframeset_erase_duplicate(usedframes);
  muse_cplframeset_erase_duplicate(outframes);

  /* to get esorex to see our classification (frame groups etc.), *
   * replace the original frameset with the list of used frames   *
   * before appending product output frames                       */
  /* keep the same pointer, so just erase all frames, not delete the frameset */
  muse_cplframeset_erase_all(recipe->frames);
  cpl_frameset_join(recipe->frames, usedframes);
  cpl_frameset_join(recipe->frames, outframes);
  cpl_frameset_delete(usedframes);
  cpl_frameset_delete(outframes);
  return rc;
} /* muse_twilight_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_twilight_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_twilight_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_twilight_help,
                           muse_twilight_help_esorex);
  } else {
    helptext = cpl_sprintf("%s", muse_twilight_help);
  }

  /* Initialize the CPL plugin stuff for this module */
  cpl_plugin_init(plugin, CPL_PLUGIN_API, MUSE_BINARY_VERSION,
                  CPL_PLUGIN_TYPE_RECIPE,
                  "muse_twilight",
                  "Combine several twilight skyflats into one cube, compute correction factors for each IFU, and create a smooth 3D illumination correction.",
                  helptext,
                  "Peter Weilbacher",
                  "usd-help@eso.org",
                  muse_get_license(),
                  muse_twilight_create,
                  muse_twilight_exec,
                  muse_twilight_destroy);
  cpl_pluginlist_append(aList, plugin);
  cpl_free(helptext);

  return 0;
} /* cpl_plugin_get_info() */

/**@}*/