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

/*----------------------------------------------------------------------------*/
/**
  @defgroup recipe_muse_lingain         Recipe muse_lingain: Compute the gain and a model of the residual non-linearity for each detector quadrant
  @author Ralf Palsa
  
        The recipe uses the bias and flat field images of a detector monitoring
        exposure sequence to determine the detector gain in counts/ADU and to
        model the residual non-linearity for each of the four detector quadrants
        of all IFUs.

        All measurements done by the recipe are done on the illuminated parts
        of the detector, i.e. on the slices. The location of the slices is
        taken from the given trace table, which is a mandatory input. Using the
        traces of the slices on the detector a set of measurement windows is
        placed along these traces. The data used for the determination of the
        gain and the residual non-linearity is the taken from these windows.

        Bad pixels indicated by an, optionally, provided bad pixel table, or
        flagged during the preprocessing (bias subtraction) of the input data
        are excluded from the measurements.

        Local measurements of the read-out-noise, the signal and the gain are
        calculated for each of the measurement windows. Using these measurements
        the gain for each detector quadrant is computed as the zero-order
        coefficient of a 1st order polynomial fitted to the binned gain
        measurements as a function of the signal level.

        The residual non-linearity is modelled by a (high) order polynomial
        which is fitted to the fractional percentage deviation of the count
        rate from an expected constant count rate (the linear case) as function
        of the signal level. (Not yet implemented!)
      
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*----------------------------------------------------------------------------*
 *                         Static variables                                   *
 *----------------------------------------------------------------------------*/
static const char *muse_lingain_help =
  "The recipe uses the bias and flat field images of a detector monitoring exposure sequence to determine the detector gain in counts/ADU and to model the residual non-linearity for each of the four detector quadrants of all IFUs. All measurements done by the recipe are done on the illuminated parts of the detector, i.e. on the slices. The location of the slices is taken from the given trace table, which is a mandatory input. Using the traces of the slices on the detector a set of measurement windows is placed along these traces. The data used for the determination of the gain and the residual non-linearity is the taken from these windows. Bad pixels indicated by an, optionally, provided bad pixel table, or flagged during the preprocessing (bias subtraction) of the input data are excluded from the measurements. Local measurements of the read-out-noise, the signal and the gain are calculated for each of the measurement windows. Using these measurements the gain for each detector quadrant is computed as the zero-order coefficient of a 1st order polynomial fitted to the binned gain measurements as a function of the signal level. The residual non-linearity is modelled by a (high) order polynomial which is fitted to the fractional percentage deviation of the count rate from an expected constant count rate (the linear case) as function of the signal level. (Not yet implemented!)";

static const char *muse_lingain_help_esorex =
  "\n\nInput frames for raw frame tag \"LINGAIN_LAMP_OFF\":\n"
  "\n Frame tag            Type Req #Fr Description"
  "\n -------------------- ---- --- --- ------------"
  "\n LINGAIN_LAMP_OFF     raw   Y  >=2 Detector monitoring bias images"
  "\n LINGAIN_LAMP_ON      raw   Y  >=2 Detector monitoring flat field images"
  "\n MASTER_BIAS          calib Y    1 Master bias"
  "\n TRACE_TABLE          calib Y    1 Trace table"
  "\n BADPIX_TABLE         calib .      Known bad pixels"
  "\n\nProduct frames for raw frame tag \"LINGAIN_LAMP_OFF\":\n"
  "\n Frame tag            Level    Description"
  "\n -------------------- -------- ------------"
  "\n NONLINEARITY_GAIN    final    List of non-linearity and gain parameters for each detector readout port.";

/*----------------------------------------------------------------------------*/
/**
  @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_lingain_new_recipeconfig(void)
{
  cpl_recipeconfig *recipeconfig = cpl_recipeconfig_new();
      
  cpl_recipeconfig_set_tag(recipeconfig, "LINGAIN_LAMP_OFF", 2, -1);
  cpl_recipeconfig_set_input(recipeconfig, "LINGAIN_LAMP_OFF", "MASTER_BIAS", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "LINGAIN_LAMP_OFF", "TRACE_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "LINGAIN_LAMP_OFF", "BADPIX_TABLE", -1, -1);
  cpl_recipeconfig_set_output(recipeconfig, "LINGAIN_LAMP_OFF", "NONLINEARITY_GAIN");
  cpl_recipeconfig_set_tag(recipeconfig, "LINGAIN_LAMP_ON", 2, -1);
  cpl_recipeconfig_set_input(recipeconfig, "LINGAIN_LAMP_ON", "MASTER_BIAS", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "LINGAIN_LAMP_ON", "TRACE_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "LINGAIN_LAMP_ON", "BADPIX_TABLE", -1, -1);
  cpl_recipeconfig_set_output(recipeconfig, "LINGAIN_LAMP_ON", "NONLINEARITY_GAIN");
    
  return recipeconfig;
} /* muse_lingain_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_lingain_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, "NONLINEARITY_GAIN")) {
    muse_processing_prepare_property(aHeader, "ESO QC LINGAIN OUT[1234] COUNTS MIN",
                                     CPL_TYPE_DOUBLE,
                                     "[ADU] Minimum signal level in measurement region");
    muse_processing_prepare_property(aHeader, "ESO QC LINGAIN OUT[1234] COUNTS MAX",
                                     CPL_TYPE_DOUBLE,
                                     "[ADU] Maximum signal level in measurement region");
    muse_processing_prepare_property(aHeader, "ESO QC LINGAIN OUT[1234] RON",
                                     CPL_TYPE_DOUBLE,
                                     "[count] Read-out noise measured per quadrant as weighted mean.");
    muse_processing_prepare_property(aHeader, "ESO QC LINGAIN OUT[1234] RONERR",
                                     CPL_TYPE_DOUBLE,
                                     "[count] Read-out noise error estimate");
    muse_processing_prepare_property(aHeader, "ESO QC LINGAIN OUT[1234] RON MEDIAN",
                                     CPL_TYPE_DOUBLE,
                                     "[count] Median read-out noise");
    muse_processing_prepare_property(aHeader, "ESO QC LINGAIN OUT[1234] RON MAD",
                                     CPL_TYPE_DOUBLE,
                                     "[count] MAD of the read-out noise measurements");
    muse_processing_prepare_property(aHeader, "ESO QC LINGAIN OUT[1234] CONAD",
                                     CPL_TYPE_DOUBLE,
                                     "[ADU/count] Conversion factor calculated as the inverse of the measured gain");
    muse_processing_prepare_property(aHeader, "ESO QC LINGAIN OUT[1234] GAIN",
                                     CPL_TYPE_DOUBLE,
                                     "[count/ADU] Gain value as determined from a first order fit");
    muse_processing_prepare_property(aHeader, "ESO QC LINGAIN OUT[1234] GAINERR",
                                     CPL_TYPE_DOUBLE,
                                     "[count/ADU] RMS of the first order polynomial fit used to determine the gain");
  } else {
    cpl_msg_warning(__func__, "Frame tag %s is not defined", aFrametag);
    return CPL_ERROR_ILLEGAL_INPUT;
  }
  return CPL_ERROR_NONE;
} /* muse_lingain_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_lingain_get_frame_level(const char *aFrametag)
{
  if (!aFrametag) {
    return CPL_FRAME_LEVEL_NONE;
  }
  if (!strcmp(aFrametag, "NONLINEARITY_GAIN")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  return CPL_FRAME_LEVEL_NONE;
} /* muse_lingain_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_lingain_get_frame_mode(const char *aFrametag)
{
  if (!aFrametag) {
    return MUSE_FRAME_MODE_ALL;
  }
  if (!strcmp(aFrametag, "NONLINEARITY_GAIN")) {
    return MUSE_FRAME_MODE_MASTER;
  }
  return MUSE_FRAME_MODE_ALL;
} /* muse_lingain_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_lingain_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_lingain_new_recipeconfig(),
                               muse_lingain_prepare_header,
                               muse_lingain_get_frame_level,
                               muse_lingain_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_lingain.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_lingain",
                              (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);
      
  /* --ybox: 
          Size of windows along the traces of the slices.
         */
  p = cpl_parameter_new_value("muse.muse_lingain.ybox",
                              CPL_TYPE_INT,
                             "Size of windows along the traces of the slices.",
                              "muse.muse_lingain",
                              (int)50);
  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);
      
  /* --xgap: 
          Extra offset from tracing edge.
         */
  p = cpl_parameter_new_value("muse.muse_lingain.xgap",
                              CPL_TYPE_INT,
                             "Extra offset from tracing edge.",
                              "muse.muse_lingain",
                              (int)3);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "xgap");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "xgap");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --xborder: 
          Extra offset from the detector edge used for the selection of slices.
         */
  p = cpl_parameter_new_value("muse.muse_lingain.xborder",
                              CPL_TYPE_INT,
                             "Extra offset from the detector edge used for the selection of slices.",
                              "muse.muse_lingain",
                              (int)10);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "xborder");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "xborder");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --order: 
          Order of the polynomial used to fit the non-linearity residuals.
         */
  p = cpl_parameter_new_value("muse.muse_lingain.order",
                              CPL_TYPE_INT,
                             "Order of the polynomial used to fit the non-linearity residuals.",
                              "muse.muse_lingain",
                              (int)12);
  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);
      
  /* --toffset: 
          Exposure time offset in seconds to apply to linearity flat fields.
         */
  p = cpl_parameter_new_value("muse.muse_lingain.toffset",
                              CPL_TYPE_DOUBLE,
                             "Exposure time offset in seconds to apply to linearity flat fields.",
                              "muse.muse_lingain",
                              (double)0.018);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "toffset");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "toffset");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --fluxtol: 
          Tolerance value for the overall flux consistency check of a pair of flat fields. The value is the maximum relative offset.
         */
  p = cpl_parameter_new_value("muse.muse_lingain.fluxtol",
                              CPL_TYPE_DOUBLE,
                             "Tolerance value for the overall flux consistency check of a pair of flat fields. The value is the maximum relative offset.",
                              "muse.muse_lingain",
                              (double)0.01);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "fluxtol");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "fluxtol");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --sigma: Sigma value used for signal value clipping. */
  p = cpl_parameter_new_value("muse.muse_lingain.sigma",
                              CPL_TYPE_DOUBLE,
                             "Sigma value used for signal value clipping.",
                              "muse.muse_lingain",
                              (double)3.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "sigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "sigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --signalmin: Minimum signal value in log(ADU) used for the gain analysis and the non-linearity polynomial model. */
  p = cpl_parameter_new_value("muse.muse_lingain.signalmin",
                              CPL_TYPE_DOUBLE,
                             "Minimum signal value in log(ADU) used for the gain analysis and the non-linearity polynomial model.",
                              "muse.muse_lingain",
                              (double)0.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "signalmin");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "signalmin");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --signalmax: Maximum signal value in log(ADU) used for the gain analysis and the non-linearity polynomial model. */
  p = cpl_parameter_new_value("muse.muse_lingain.signalmax",
                              CPL_TYPE_DOUBLE,
                             "Maximum signal value in log(ADU) used for the gain analysis and the non-linearity polynomial model.",
                              "muse.muse_lingain",
                              (double)4.9);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "signalmax");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "signalmax");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --signalbin: Size of a signal bin in log10(ADU) used for the gain analysis and the non-linearity polynomial model. */
  p = cpl_parameter_new_value("muse.muse_lingain.signalbin",
                              CPL_TYPE_DOUBLE,
                             "Size of a signal bin in log10(ADU) used for the gain analysis and the non-linearity polynomial model.",
                              "muse.muse_lingain",
                              (double)0.1);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "signalbin");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "signalbin");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --gainlimit: Minimum signal value [ADU] used for fitting the gain relation. */
  p = cpl_parameter_new_value("muse.muse_lingain.gainlimit",
                              CPL_TYPE_DOUBLE,
                             "Minimum signal value [ADU] used for fitting the gain relation.",
                              "muse.muse_lingain",
                              (double)100.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "gainlimit");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "gainlimit");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --gainsigma: Sigma value for gain value clipping. */
  p = cpl_parameter_new_value("muse.muse_lingain.gainsigma",
                              CPL_TYPE_DOUBLE,
                             "Sigma value for gain value clipping.",
                              "muse.muse_lingain",
                              (double)3.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "gainsigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "gainsigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --ctsmin: Minimum signal value in log(counts) to consider for the non-linearity analysis. */
  p = cpl_parameter_new_value("muse.muse_lingain.ctsmin",
                              CPL_TYPE_DOUBLE,
                             "Minimum signal value in log(counts) to consider for the non-linearity analysis.",
                              "muse.muse_lingain",
                              (double)3.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "ctsmin");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ctsmin");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --ctsmax: Maximum signal value in log(counts) to consider for the non-linearity analysis. */
  p = cpl_parameter_new_value("muse.muse_lingain.ctsmax",
                              CPL_TYPE_DOUBLE,
                             "Maximum signal value in log(counts) to consider for the non-linearity analysis.",
                              "muse.muse_lingain",
                              (double)4.9);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "ctsmax");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ctsmax");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --ctsbin: Size of a signal bin in log10(counts) used for the non-linearity analysis. */
  p = cpl_parameter_new_value("muse.muse_lingain.ctsbin",
                              CPL_TYPE_DOUBLE,
                             "Size of a signal bin in log10(counts) used for the non-linearity analysis.",
                              "muse.muse_lingain",
                              (double)0.1);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "ctsbin");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ctsbin");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --linearmin: Lower limit of desired linear range in log10(counts). */
  p = cpl_parameter_new_value("muse.muse_lingain.linearmin",
                              CPL_TYPE_DOUBLE,
                             "Lower limit of desired linear range in log10(counts).",
                              "muse.muse_lingain",
                              (double)2.5);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "linearmin");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "linearmin");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --linearmax: Upper limit of desired linear range in log10(counts). */
  p = cpl_parameter_new_value("muse.muse_lingain.linearmax",
                              CPL_TYPE_DOUBLE,
                             "Upper limit of desired linear range in log10(counts).",
                              "muse.muse_lingain",
                              (double)3.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "linearmax");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "linearmax");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --merge: Merge output products from different IFUs into a common file. */
  p = cpl_parameter_new_value("muse.muse_lingain.merge",
                              CPL_TYPE_BOOL,
                             "Merge output products from different IFUs into a common file.",
                              "muse.muse_lingain",
                              (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_lingain_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_lingain_params_fill(muse_lingain_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_lingain.nifu");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nifu = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.ybox");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ybox = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.xgap");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->xgap = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.xborder");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->xborder = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.order");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->order = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.toffset");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->toffset = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.fluxtol");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->fluxtol = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.sigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->sigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.signalmin");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->signalmin = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.signalmax");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->signalmax = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.signalbin");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->signalbin = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.gainlimit");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->gainlimit = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.gainsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->gainsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.ctsmin");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ctsmin = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.ctsmax");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ctsmax = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.ctsbin");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ctsbin = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.linearmin");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->linearmin = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.linearmax");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->linearmax = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_lingain.merge");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->merge = cpl_parameter_get_bool(p);
    
  return 0;
} /* muse_lingain_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_lingain_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_lingain_params_t params;
  muse_lingain_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_lingain",
                                                recipe);
    rc = muse_lingain_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;
    // FIXME: Removed default(none) clause here, to make the code work with
    //        gcc9 while keeping older versions of gcc working too without
    //        resorting to conditional compilation. Having default(none) here
    //        causes gcc9 to abort the build because of __func__ not being
    //        specified in a data sharing clause. Adding a data sharing clause
    //        makes older gcc versions choke.
    #pragma omp parallel for                                                   \
            shared(outframes, params, rcs, recipe, usedframes)
    for (nifu = 1; nifu <= kMuseNumIFUs; nifu++) {
      muse_processing *proc = muse_processing_new("muse_lingain",
                                                  recipe);
      muse_lingain_params_t *pars = cpl_malloc(sizeof(muse_lingain_params_t));
      memcpy(pars, &params, sizeof(muse_lingain_params_t));
      pars->nifu = nifu;
      int *rci = rcs + (nifu - 1);
      *rci = muse_lingain_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_lingain",
                                                  recipe);
      rc = muse_lingain_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_lingain_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_lingain_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_lingain_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_lingain_help,
                           muse_lingain_help_esorex);
  } else {
    helptext = cpl_sprintf("%s", muse_lingain_help);
  }

  /* Initialize the CPL plugin stuff for this module */
  cpl_plugin_init(plugin, CPL_PLUGIN_API, MUSE_BINARY_VERSION,
                  CPL_PLUGIN_TYPE_RECIPE,
                  "muse_lingain",
                  "Compute the gain and a model of the residual non-linearity for each detector quadrant",
                  helptext,
                  "Ralf Palsa",
                  "usd-help@eso.org",
                  muse_get_license(),
                  muse_lingain_create,
                  muse_lingain_exec,
                  muse_lingain_destroy);
  cpl_pluginlist_append(aList, plugin);
  cpl_free(helptext);

  return 0;
} /* cpl_plugin_get_info() */

/**@}*/