/*                                                                              *
 *   This file is part of the ESO UVES Pipeline                                 *
 *   Copyright (C) 2004,2005 European Southern Observatory                      *
 *                                                                              *
 *   This library 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, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA       *
 *                                                                              */

/*
 * $Author: amodigli $
 * $Date: 2013-08-08 13:36:46 $
 * $Revision: 1.53 $
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

/*----------------------------------------------------------------------------*/
/**
 * @defgroup uves_reduce_mflat    Master flat reduction
 *
 */
/*----------------------------------------------------------------------------*/
/**@{*/



/*-----------------------------------------------------------------------------
                                Includes
 -----------------------------------------------------------------------------*/
#include <uves_reduce_mflat.h>

#include <uves.h>
#include <uves_backsub.h>
#include <uves_chip.h>
#include <uves_dfs.h>
#include <uves_pfits.h>
#include <uves_parameters.h>
#include <uves_utils.h>
#include <uves_utils_wrappers.h>
#include <uves_qclog.h>
#include <uves_error.h>
#include <uves_msg.h>

#include <cpl.h>
#include <float.h>
#include <string.h>
/*-----------------------------------------------------------------------------
                            Functions prototypes
 -----------------------------------------------------------------------------*/

static void uves_mflat_qclog(const cpl_imagelist* raw_images,
                     cpl_table* qclog);

static cpl_error_code uves_msflats(cpl_frameset * set, const cpl_parameterlist *parameters,
                   const char *recipe_id,
                   const char *starttime);
static void uves_mflat_one(cpl_frameset *frames,
               const cpl_parameterlist *parameters, 
               bool flames,
               const char *recipe_id,
               const char *starttime,
               const char* prefix);

static cpl_error_code
uves_mflat_at_ypos(cpl_frameset* set,
           const cpl_parameterlist* parameters,
           const char *recipe_id,
           const char *starttime,
                   const cpl_frameset* raw,
                   const cpl_frameset* cdb,
                   const int ref_x1enc,
                   const int ref_x2enc,
           const int set_no);

static void uves_reduce_mflat(cpl_frameset *frames, const cpl_parameterlist *parameters,
                  bool flames,
                  const char *recipe_id, 
                  const char *starttime,
                  const char *prefix);

/*-----------------------------------------------------------------------------
                            Implementation
 -----------------------------------------------------------------------------*/
const char * const uves_mflat_desc =
"This recipe creates a master flat frame by 1) subtracting the master bias\n"
"frame from each flat field frame, 2) dividing each flat field frame by the\n"
" exposure time for that frame, 3) taking the median of all bias subtracted,\n"
" normalized raw\n flat frames, 4) optionally subtracting the master dark \n"
"frame, and 5) subtracting\n the background to get the bias subtracted, \n"
"optionally dark subtracted, normalized, background subtracted master \n"
"flat-field frame. Symbolically,\n"
" masterflat = median( (flat_i - masterbias)/exptime_i ) - masterdark/exptime\n"
"            - background.\n"
"\n"
"The input flat field frames must have same tag which must match\n"
"(I|D|S|T|SCREEN|)FLAT_(BLUE|RED), for example TFLAT_BLUE or FLAT_RED. Also, a\n"
"master bias (MASTER_BIAS_xxxx) and ordertable (ORDER_TABLE_xxxx) must be\n"
"provided for each chip (xxxx = BLUE, REDL, REDU). A master dark frame\n"
"(MASTER_(P)DARK_xxxx) may optionally be provided. On blue input the recipe\n"
"computes one master flat field frame; on red input the recipe produces a\n"
"master flat field frame for each chip (MASTER_FLAT_xxxx, MASTER_IFLAT_xxxx,\n"
"MASTER_DFLAT_xxxx, MASTER_TFLAT_xxxx or MASTER_SCREEN_FLAT_xxxx).";

/*----------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options    
  @param    parameters   the parameterlist to fill
  @param    recipe_id    name of calling recipe
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
int
uves_mflat_define_parameters_body(cpl_parameterlist *parameters, 
                  const char *recipe_id)
{

   cpl_parameter* p=NULL;
   /*****************
    *    General    *
    *****************/
   if (uves_define_global_parameters(parameters) != CPL_ERROR_NONE)
   {
      return -1;
   }
   if (uves_corr_traps_define_parameters(parameters,recipe_id) 
       != CPL_ERROR_NONE)
   {
      return -1;
   }

    /**************************************
     *  Master stack generation           *
     **************************************/
    if (uves_master_flat_define_parameters(parameters,recipe_id) 
        != CPL_ERROR_NONE)
    {
            return -1;
    }

    if(strcmp(recipe_id,"flames_cal_mkmaster") ==0) {
       check_nomsg(p=cpl_parameterlist_find(parameters,"flames_cal_mkmaster.norm_method"));
       cpl_parameter_set_string(p,"exptime");
    }
  cleanup:
/*
    if (uves_master_stack_define_parameters(parameters,recipe_id) 
        != CPL_ERROR_NONE)
        {
            return -1;
        }
*/
    
    /****************************
     *  Spline back.sub.        *
     ****************************/
    
    if (uves_propagate_parameters_step(UVES_BACKSUB_ID, parameters, 
                       recipe_id, NULL) != 0)
    {
        return -1;
    }



    return (cpl_error_get_code() != CPL_ERROR_NONE);
}

/*----------------------------------------------------------------------------*/
/**
   @brief    Process a single chip
   @param    raw_images          The input images
   @param    raw_headers         An array containing the input image headers. The ordering
                                 must be the same as the ordering of images in the 
                 input image list
   @param    master_flat_header  This header is updated with the normalized exposure time
   @param    master_bias         The master bias image for this chip, or NULL
   @param    master_dark         If non-null this master dark frame is subtracted
   @param    mdark_header        The header of the master dark frame (used only if 
                                 @em master_dark is non-null).
   @param    ordertable          The order table for this chip. Used for background
                                 subtraction.
   @param    order_locations     Polynomial defining the order locations. Used for
                                 background subtraction.
   @param    flames              FLAMES reduction? In this case the background image
                                 is not computed/subtracted
   @param    parameters          The recipe parameter list
   @param    chip                CCD chip
   @param    recipe_id           name of calling recipe
   @param    debug_mode               Save intermediate results to disk?
   @param    background          (output) The background image which was subtracted

   @return   The master flat image
 
   This function
   - subtracts from each input image the provided @em master bias,
   - rescales each input image to unit exposure time by dividing by the exposure
   time read from the image header.
   - computes the master flat image by taking the pixel-by-pixel median of all input frames,
   - optionally subtracts the normalized master dark frame, and
   - subtracts the background (see @c uves_backsub_spline()) .

   masterflat = median( (flat_i - masterbias)/exptime_i ) - masterdark/exptime_mdark - background

   Dark subtraction is optional and is done only if the parameter @em master_dark is non-NULL.
*/
/*----------------------------------------------------------------------------*/
static cpl_image *
uves_mflat_process_chip(const cpl_imagelist *raw_images, 
                        uves_propertylist **raw_headers, 
                        uves_propertylist *master_flat_header,
                        const cpl_image *master_bias,
                        const cpl_image *master_dark, 
                        const uves_propertylist *mdark_header, 
                        const cpl_table *ordertable, 
                        const polynomial *order_locations,
                        bool flames,
                        const cpl_parameterlist *parameters,
                        enum uves_chip chip,
                        const char *recipe_id,
                        bool debug_mode,
                        cpl_image **background)

{
    cpl_image *master_flat        = NULL; /* Result */
    cpl_image *master_flat_tmp        = NULL; /* Result */

    cpl_image *current_flat       = NULL;
   
    int i;
    const char* FLAT_METHOD=NULL;
    cpl_vector* exptimes=NULL;
    cpl_vector* gain_vals=NULL;
    double mdark_exposure=0;
    cpl_image* mdark_scaled=NULL;
    double fnoise=0;
    double gain=0;
    cpl_imagelist *raw_images_local=NULL;

    /* First process each input image and store the results in a new image list */
   /* Get recipe parameters */
  check( uves_get_parameter(parameters, NULL, recipe_id, "norm_method", 
             CPL_TYPE_STRING, &FLAT_METHOD),
               "Could not read parameter");
    uves_string_toupper((char*)FLAT_METHOD);
    
    raw_images_local=(cpl_imagelist*) raw_images;
    exptimes=cpl_vector_new(cpl_imagelist_get_size(raw_images));
    gain_vals=cpl_vector_new(cpl_imagelist_get_size(raw_images));
    /* to remove compiler warnings */
    for (i = 0; i < cpl_imagelist_get_size(raw_images); i++)
    {
        double exposure_time = 0.0;

        const uves_propertylist *current_header = NULL;

        current_flat   = cpl_image_duplicate(cpl_imagelist_get_const(raw_images, i));
        current_header = raw_headers[i];
        
        /* Subtract master bias */
        if (master_bias != NULL)
        {
            uves_msg("Subtracting master bias");
            check( uves_subtract_bias(current_flat, master_bias), 
               "Error subtracting master bias");
        }
        else
        {
            uves_msg("Skipping bias subtraction");
        }
        
        /* Normalize to unit exposure time:  */
        check( exposure_time = uves_pfits_get_exptime(current_header),
           "Error reading exposure time");
        check( gain = uves_pfits_get_gain(current_header,chip), 
           "Error reading gain value");
        
        uves_msg("Normalizing flat from %f s to unit exposure time", exposure_time);
        check( cpl_image_divide_scalar(current_flat, exposure_time),
           "Error normalizing flat field");
        check( uves_pfits_set_exptime(master_flat_header, 1.0),
           "Error writing master frame exposure time");
        cpl_vector_set(exptimes,i,exposure_time);
        cpl_vector_set(gain_vals,i,gain);

        /* Append to imagelist */
        check( cpl_imagelist_set(raw_images_local,     /* Image list */
                     current_flat,       /* Image to insert */
                     i),                 /* Position (number_of_images=>append) */
           "Could not insert image into image list");
        
        /* Don't deallocate the image. It will be deallocated when
           the image list is deallocated */
        current_flat = NULL;
    }

    /* subtract master dark if present */
    if (master_dark != NULL)
    {
        uves_msg("Subtracting master dark scaled to unit exposure time");
        check_nomsg( mdark_exposure = uves_pfits_get_exptime(mdark_header));

        mdark_scaled=cpl_image_duplicate(master_dark);
        cpl_image_divide_scalar(mdark_scaled,mdark_exposure); 
        check( cpl_imagelist_subtract_image(raw_images_local,mdark_scaled), 
           "Error subtracting master dark");
        uves_free_image(&mdark_scaled);
    }
    else
    {
        uves_msg("Skipping dark subtraction");
    }

    
    /* Take median of all input flats */
    if(strcmp(FLAT_METHOD,"EXPTIME")==0) {
       uves_msg("Calculating stack median");
       check(master_flat=cpl_imagelist_collapse_median_create(raw_images_local), 
              "Error computing median");
    } else {
       uves_msg("Calculating stack normalized master");
       check( master_flat_tmp = uves_flat_create_normalized_master(raw_images_local,
								   ordertable,
								   order_locations,gain_vals,&fnoise),
              "Error computing master flat with normalization");

      check( master_flat = uves_flat_create_normalized_master2(raw_images_local,
                                                               ordertable,
                                                              order_locations,
                                                               master_flat_tmp),
              "Error computing master flat with normalization");
      uves_free_image(&master_flat_tmp);
      uves_propertylist_append_c_double(master_flat_header,UVES_FNOISE,fnoise,
                                          "Master flat RMS on frame");

    }
    /*clean mem and reset local pointers to null */
    raw_images_local=NULL;
    uves_free_vector(&exptimes);
    uves_free_vector(&gain_vals);

    if (debug_mode && !flames)
    {
        check( uves_save_image_local("Pre-background subtracted master flat", "pre",
                                     master_flat, chip, -1, -1, master_flat_header, true), 
           "Error saving image");
    }
    
    /* Subtract background from master flat */
    if (!flames)
    {
        uves_msg("Subtracting background");
        
        check( uves_backsub_spline(master_flat, 
                       /* Info about chip (wavelength, ...) is 
                      stored in any raw header,
                      so just pass the first one   */
                       raw_headers[0],                
                       ordertable, order_locations, 
                       parameters, recipe_id,
                       chip,
                       true,     /* Use flat-field parameters? */
                       background),
           "Error subtracting background from master flat");
    }
    else
    {
        uves_msg("Skipping background subtraction");
    }
    //uves_pfits_set_extname(master_flat_header,"Master flat");
  cleanup:


    uves_free_image(&current_flat);
    if (cpl_error_get_code() != CPL_ERROR_NONE)
    {
        uves_free_image(&master_flat);
    }
    
    return master_flat;
}

/*----------------------------------------------------------------------------*/
/**
   @brief    Get the command line options and execute the data reduction
   @param    parameters  the parameters list
   @param    frames      the frames list
   @return   CPL_ERROR_NONE if everything is ok

   After computing the master flat frame, the pixel average, standard deviation
   and median values are also computed and written in appropriate keywords in the
   output image header.

*/
/*----------------------------------------------------------------------------*/
void
uves_mflat_exe_body(cpl_frameset *frames, 
                    const cpl_parameterlist *parameters,
                    const char *starttime,
                    const char *recipe_id)
{
    /* Do FLAMES reduction if SFLAT frame is given */
    if (cpl_frameset_find(frames, UVES_SFLAT(false)) != NULL) {
  
        check(uves_msflats(frames, parameters, recipe_id, starttime),
              "find same sflats failed");
    }
    else {
        bool flames = false;
        check(uves_mflat_one(frames, parameters, flames, recipe_id, 
                             starttime, ""),
              "Master flat one failed");
    }
    
 cleanup:
    return;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Computes coherent master sflats 
  @param    set     The input frameset
  @return   CPL_ERROR_NONE iff ok
 */
/*----------------------------------------------------------------------------*/
static cpl_error_code
uves_msflats(cpl_frameset * set, const cpl_parameterlist *parameters,
         const char *recipe_id,
         const char *starttime)
{
  /* Pseudocode:
     extract raw frames from set
     extract cdb frames from set
     identifies how many different Y position we have 
     for each Y pos:
         extract from the raw_set the raw frames corresponding to each Y pos 
         merge in a new wrk_set the cdb_set 
         computes the corresponding master flat 
         put the products in the final set 
     endfor 
  */
  cpl_frameset* raw=NULL;
  cpl_frameset* cdb=NULL;
  cpl_frameset* pro=NULL;
  int status=0;
  int x1enc=0;
  int x2enc=0;

  cpl_table* encoder_tbl=NULL;
  int nset=0;
  int i=0;

  //Extracts SFLAT raw frames 
  check(raw=uves_frameset_extract(set,UVES_SFLAT(false)),
				  "Extract %s frames failed",
				  UVES_SFLAT(false));

  check(uves_extract_frames_group_type(set,&cdb,CPL_FRAME_GROUP_CALIB),
    "Extract cdb frames failed");
  check(uves_sflats_get_encoder_steps(raw,&encoder_tbl,&nset),
    "Get encoder steps failed");
  uves_msg("Check Slit Flat Field Y nominal positions within each set");
  for(i=0;i<nset;i++) {

         uves_msg("Slit Flat field set %d: x1enc = %d x2enc = %d",
              i+1,
              cpl_table_get_int(encoder_tbl,"x1enc",i,&status),
              cpl_table_get_int(encoder_tbl,"x2enc",i,&status));

  }

  for(i=0;i<nset;i++) {
    x1enc=cpl_table_get_int(encoder_tbl,"x1enc",i,&status);
    x2enc=cpl_table_get_int(encoder_tbl,"x2enc",i,&status);

    uves_msg("Processing set %d", i+1);
   
    check(uves_mflat_at_ypos(set,parameters,recipe_id,starttime,raw,cdb,x1enc,x2enc,i+1),
      "Master flat one failed");
  }

  cleanup:
  uves_free_table(&encoder_tbl);
  uves_free_frameset(&raw);
  uves_free_frameset(&cdb);
  uves_free_frameset(&pro);

    return cpl_error_get_code();
}


/*----------------------------------------------------------------------------*/
/**
  @brief    Computes coherent master sflats 
  @param    set     The input frameset
  @return   CPL_ERROR_NONE iff ok
 */
/*----------------------------------------------------------------------------*/
static cpl_error_code
uves_mflat_at_ypos(cpl_frameset* set,
           const cpl_parameterlist* parameters,
           const char *recipe_id,
           const char *starttime,
                   const cpl_frameset* raw,
                   const cpl_frameset* cdb,
                   const int ref_x1enc,
                   const int ref_x2enc,
                   const int set_no)
{

    const cpl_frame* frm_tmp=NULL;
  char* file=NULL;
  uves_propertylist* plist=NULL;
  cpl_size i=0;
  const int threshold = 5;
  cpl_frame* frm_dup=NULL;
  cpl_frameset* tmp=NULL;
  cpl_frameset* pro=NULL;
  int x1enc=0;
  int x2enc=0;
  char prefix[255];
  bool flames = true;

  check_nomsg(tmp=cpl_frameset_new());
   for(i=0;i<cpl_frameset_get_size(raw);i++)
    {
    check_nomsg(frm_tmp=cpl_frameset_get_frame_const(raw,i));
    check_nomsg(file=cpl_strdup(cpl_frame_get_filename(frm_tmp)));
    check_nomsg(plist=uves_propertylist_load(file,0));
    check_nomsg(x1enc=uves_pfits_get_slit3_x1encoder(plist));
    check_nomsg(x2enc=uves_pfits_get_slit3_x2encoder(plist));
    
    if( (fabs(x1enc - ref_x1enc) <= threshold) &&
        (fabs(x2enc - ref_x2enc) <= threshold) ) {
      uves_msg_debug("file=%s x1enc=%d x2enc=%d",file,x1enc,x2enc);
      check(frm_dup = cpl_frame_duplicate(frm_tmp),"duplicate");
      check(cpl_frameset_insert(tmp,frm_dup),"insert");
    }
    cpl_free(file);
    uves_free_propertylist(&plist);
    }
   check_nomsg(uves_frameset_merge(tmp,cdb));
   sprintf(prefix,"%s%d%s","set",set_no,"_");
   check(uves_mflat_one(tmp,parameters, flames, recipe_id, starttime,prefix),"Master flat one failed");
   check_nomsg(uves_extract_frames_group_type(tmp,&pro,CPL_FRAME_GROUP_PRODUCT));
   check_nomsg(uves_frameset_merge(set,pro));

 cleanup:
   uves_free_frameset(&tmp);
   uves_free_frameset(&pro);
   uves_free_propertylist(&plist);
  
    return cpl_error_get_code();
}
/*----------------------------------------------------------------------------*/
/**
   @brief    Get the command line options and execute the data reduction
   @param    frames      the frames list
   @param    parameters  the parameters list
   @parma    flames      FLAMES mode?
   @return   CPL_ERROR_NONE if everything is ok

   After computing the master flat frame, the pixel average, standard deviation
   and median values are also computed and written in appropriate keywords in the
   output image header.

*/
/*----------------------------------------------------------------------------*/
static void
uves_mflat_one(cpl_frameset *frames,
           const cpl_parameterlist *parameters, 
           bool flames,
           const char *recipe_id,
           const char *starttime,
               const char* prefix)
{
    /* Do flat-fielding */
    check_nomsg( uves_reduce_mflat(frames, parameters, 
                   flames, recipe_id,
                   starttime, prefix) );

  cleanup:
    return;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Get the command line options and execute the data reduction
  @param    frames      the frames list
  @param    parameters  the parameters list
  @param    flames      Called by FLAMES recipe?
  @param    recipe_id   the recipe name (will be written to FITS headers)
  @param    starttime   time when calling recipe started
  @param    prefix      tag prefix as x in 'xFLAT'
  @return   CPL_ERROR_NONE if everything is ok
 */
/*----------------------------------------------------------------------------*/
static void
uves_reduce_mflat(cpl_frameset *frames, const cpl_parameterlist *parameters,
          bool flames,
          const char *recipe_id, 
          const char *starttime,
          const char *prefix)
{
    bool debug_mode;

    /* Input */
    cpl_imagelist       *raw_images[2] = {NULL, NULL}; /* An image list for both chips */
    uves_propertylist  **raw_headers[2] = {NULL, NULL}; /* Two arrays of pointers */

    /* Master bias */
    cpl_image *master_bias               = NULL;
    uves_propertylist *master_bias_header = NULL;

    /* Master dark */
    cpl_image *master_dark               = NULL;
    uves_propertylist *master_dark_header = NULL;

    /* Order table */
    cpl_table        *ordertable            = NULL;
    uves_propertylist *ordertable_header     = NULL;
    polynomial       *order_locations       = NULL;
    cpl_table        *traces                = NULL;
    
    /* Reference master flat */
    cpl_image        *ref_flat              = NULL;
    uves_propertylist *ref_flat_header       = NULL;

    /* Output */
    cpl_table *qclog[]                  = {NULL, NULL};
    cpl_image *master_flat              = NULL;
    cpl_image *background               = NULL;
    uves_propertylist *product_header[]  = {NULL, NULL};
    cpl_image *ratio                    = NULL;
    
    /* Local variables */
    char *product_filename = NULL;
    char pro_filename[255];
    const char *product_tag[2] = {NULL, NULL};
    bool blue;
    enum uves_chip chip;
    const char* PROCESS_CHIP=NULL;




    const char *ordertable_filename = "";
    const char *master_bias_filename = "";
    const char *master_dark_filename = "";
    const char *chip_name = "";
    int raw_index = 0;
    const char *ref_flat_filename;

    /* Read recipe parameters */
    {
    /* General */
    check( uves_get_parameter(parameters, NULL, "uves", "debug", CPL_TYPE_BOOL  , &debug_mode ), 
           "Could not read parameter");
    }
    check( uves_get_parameter(parameters, NULL, "uves", "process_chip", CPL_TYPE_STRING, &PROCESS_CHIP), "Could not read parameter");

    uves_string_toupper((char*)PROCESS_CHIP);

    /* Load and check raw flat images and headers, identify arm (blue/red) */
    /* On success, 'raw_headers' will be an array with the same size as 'raw_images' */
    /* Set product tags to match input tag */

    if (cpl_frameset_find(frames, UVES_FLAT(true )) != NULL ||
    cpl_frameset_find(frames, UVES_FLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_FLAT(true), UVES_FLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat frames");
        
        for (chip = uves_chip_get_first(blue); chip != UVES_CHIP_INVALID; 
         chip = uves_chip_get_next(chip))
        {
            product_tag[uves_chip_get_index(chip)] = UVES_MASTER_FLAT(chip);
        }
    }
    else if (cpl_frameset_find(frames, UVES_DFLAT(true )) != NULL ||
         cpl_frameset_find(frames, UVES_DFLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_DFLAT(true), UVES_DFLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat frames");
        for (chip = uves_chip_get_first(blue); 
         chip != UVES_CHIP_INVALID; 
         chip = uves_chip_get_next(chip))
        {
            product_tag[uves_chip_get_index(chip)] = UVES_MASTER_DFLAT(chip);
        }
    }
    else if  (cpl_frameset_find(frames, UVES_IFLAT(true )) != NULL ||
          cpl_frameset_find(frames, UVES_IFLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_IFLAT(true), UVES_IFLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat frames");
        for (chip = uves_chip_get_first(blue); 
         chip != UVES_CHIP_INVALID; 
         chip = uves_chip_get_next(chip))
        {
            product_tag[uves_chip_get_index(chip)] = UVES_MASTER_IFLAT(chip);
        }
    }
    else if  (cpl_frameset_find(frames, UVES_TFLAT(true )) != NULL ||
          cpl_frameset_find(frames, UVES_TFLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_TFLAT(true), UVES_TFLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat frames");
        for (chip = uves_chip_get_first(blue); 
         chip != UVES_CHIP_INVALID; 
         chip = uves_chip_get_next(chip))
        {
            product_tag[uves_chip_get_index(chip)] = UVES_MASTER_TFLAT(chip);
        }
    }
    else if  (cpl_frameset_find(frames, UVES_SCREEN_FLAT(true )) != NULL ||
          cpl_frameset_find(frames, UVES_SCREEN_FLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_SCREEN_FLAT(true), UVES_SCREEN_FLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat frames");
        for (chip = uves_chip_get_first(blue); 
         chip != UVES_CHIP_INVALID; 
         chip = uves_chip_get_next(chip))
        {
            product_tag[uves_chip_get_index(chip)] = UVES_MASTER_SCREEN_FLAT(chip);
        }
    }
    else if  (cpl_frameset_find(frames, UVES_SFLAT(true )) != NULL ||
          cpl_frameset_find(frames, UVES_SFLAT(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       flames,
                       UVES_SFLAT(true), UVES_SFLAT(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw flat frames");
        for (chip = uves_chip_get_first(blue); 
         chip != UVES_CHIP_INVALID; 
         chip = uves_chip_get_next(chip))
        {
            product_tag[uves_chip_get_index(chip)] = UVES_MASTER_SFLAT(chip);
        }
    }
    else 
    {
        assure(false, CPL_ERROR_DATA_NOT_FOUND,
           "Missing input flat frame: "
           "%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s or %s expected",
           UVES_FLAT(true) , UVES_FLAT(false),
           UVES_DFLAT(true), UVES_DFLAT(false),
           UVES_IFLAT(true), UVES_IFLAT(false),
           UVES_TFLAT(true), UVES_TFLAT(false),
           UVES_SCREEN_FLAT(true), UVES_SCREEN_FLAT(false),
           UVES_SFLAT(true), UVES_SFLAT(false));
    }

    /* Loop over one or two chips */
    for (chip = uves_chip_get_first(blue); 
     chip != UVES_CHIP_INVALID; 
     chip = uves_chip_get_next(chip))
    {

      if(strcmp(PROCESS_CHIP,"REDU") == 0) {
	chip = uves_chip_get_next(chip);
      }
        
        raw_index = uves_chip_get_index(chip);
        
        uves_msg("Processing %s chip", uves_chip_tostring_upper(chip));

        /* Chip name of first input frame */
        check_nomsg( chip_name = uves_pfits_get_chipid(raw_headers[raw_index][0], chip));

        /* Load master bias, set pointer to NULL if not present */
        uves_free_image(&master_bias);
        uves_free_propertylist(&master_bias_header);
        if (cpl_frameset_find(frames, UVES_MASTER_BIAS(chip)) != NULL)
        {
            uves_free_image(&master_bias);
            uves_free_propertylist(&master_bias_header);
            check( uves_load_mbias(frames,
                       chip_name,
                       &master_bias_filename, &master_bias,
                       &master_bias_header, chip), 
               "Error loading master bias");
            
            uves_msg_low("Using master bias in '%s'", master_bias_filename);
        }
        else
        {
            uves_msg_low("No master bias in SOF. Bias subtraction not done");
        }
    
        /* Load master dark, set pointer to NULL if not present */
        uves_free_image(&master_dark);
        uves_free_propertylist(&master_dark_header);
        if (cpl_frameset_find(frames, UVES_MASTER_DARK(chip))  != NULL ||
        cpl_frameset_find(frames, UVES_MASTER_PDARK(chip)) != NULL)
        {
            uves_free_image(&master_dark);
            uves_free_propertylist(&master_dark_header);
            check( uves_load_mdark(frames, chip_name,
                       &master_dark_filename, &master_dark,
                       &master_dark_header, chip), 
               "Error loading master dark");
            
            uves_msg_low("Using master dark in '%s'", master_dark_filename);
        }
        else
        {
            uves_msg_low("No master dark in SOF. Dark subtraction not done");
        }
    
        /* Load the order table for this chip */
        if (flames)
        /* FLAMES does not do background subtraction (here)
           and therefore does not need an ordertable */
        {
            if (cpl_frameset_find(frames, UVES_ORDER_TABLE(flames, chip)) != NULL)
            {
                uves_msg_warning("Order table (%s) is not used in FLAMES reduction",
                         UVES_ORDER_TABLE(flames, chip));
            }
        }
        else
        {
            uves_free_table       (&ordertable);
            uves_free_propertylist(&ordertable_header);
            uves_polynomial_delete(&order_locations);
            uves_free_table       (&traces);
            
            check( uves_load_ordertable(frames,
                        flames,
                        chip_name,
                        &ordertable_filename, 
                                                &ordertable,
                        &ordertable_header, 
                                                NULL,
                                                &order_locations,
                        &traces, NULL, NULL,
                                       NULL, NULL, /* fibre_pos,fibre_mask */
                        chip,
                        false),
               "Could not load order table");
            uves_msg("Using order table in '%s'", ordertable_filename);
        }

        /* Compute QC parameters and save */
        uves_msg("Computing QC parameters");
            uves_qclog_delete(&qclog[0]);
            qclog[0] = uves_qclog_init(raw_headers[raw_index][0], chip);

            check(uves_mflat_qclog(raw_images[raw_index],
                   qclog[0]),"error computing qclog");
    

       
        /* Process chip */
        uves_free_image(&master_flat);
        uves_free_image(&background);
        check( master_flat = uves_mflat_process_chip(
               raw_images[raw_index], raw_headers[raw_index],
               product_header[raw_index],
               master_bias,
               master_dark, master_dark_header,
               ordertable, order_locations,
               flames,
               parameters,
               chip,
               recipe_id,
               debug_mode,
               &background),
           "Error processing chip");

         /* Finished. Save */ 
        uves_msg("Saving products");
    
        cpl_free(product_filename);
        check( product_filename = uves_masterflat_filename(chip), 
               "Error getting filename");
        strcpy(pro_filename,prefix);
        strcat(pro_filename,product_filename);
        check( uves_frameset_insert(
                   frames,
                   master_flat,
                   CPL_FRAME_GROUP_PRODUCT,
                   CPL_FRAME_TYPE_IMAGE,
                   CPL_FRAME_LEVEL_INTERMEDIATE,
                   pro_filename,
                   product_tag[raw_index],
                   raw_headers[raw_index][0],
                   product_header[raw_index],
                   NULL,
                   parameters,
                   recipe_id,
                   PACKAGE "/" PACKAGE_VERSION, qclog,
                   starttime, true, UVES_ALL_STATS),
               "Could not add master flat %s %s to frameset", 
               product_filename, product_tag[raw_index]);
        uves_msg("Master flat %s %s added to frameset", 
                 pro_filename, product_tag[raw_index]);

        /* Save background image */
        if (!flames)
        {
            cpl_free(product_filename);
            check( product_filename = uves_masterflat_bkg_filename(chip), 
               "Error getting filename");
            strcpy(pro_filename,prefix);
            strcat(pro_filename,product_filename);
            //uves_pfits_set_extname(product_header[raw_index],"Inter-order background");
            check( uves_frameset_insert(frames,
                        background,
                        CPL_FRAME_GROUP_PRODUCT,
                        CPL_FRAME_TYPE_IMAGE,
                        CPL_FRAME_LEVEL_INTERMEDIATE,
                        pro_filename,
                        UVES_BKG_FLAT(chip),
                        raw_headers[raw_index][0],
                        product_header[raw_index],
                        NULL,
                        parameters,
                        recipe_id,
                        PACKAGE "/" PACKAGE_VERSION, NULL,
                        starttime, false, 
                        CPL_STATS_MIN | CPL_STATS_MAX),
               "Could not add background image '%s' to frameset", 
               product_filename);
            uves_msg("Master flat background '%s' added to frameset", 
                 product_filename);
                }

        /* Compute and save ratio MASTER_TFLAT / REF_TFLAT */
        if (strcmp(recipe_id, make_str(UVES_TFLAT_ID)) == 0)
        {

            uves_free_image(&ref_flat);
            uves_free_propertylist(&ref_flat_header);

            check( uves_load_ref_flat(frames, chip_name, &ref_flat_filename, 
                          &ref_flat, &ref_flat_header, 
                          chip),
               "Error loading reference flat field");
            
            uves_msg("Using reference flat field in '%s'", ref_flat_filename);

            check( ratio = cpl_image_divide_create(master_flat, ref_flat),
               "Error computing ratio of master and reference flat");

            cpl_free(product_filename);
            check( product_filename = uves_flat_ratio_filename(chip), 
               "Error getting filename");
            
            check( uves_frameset_insert(frames,
                        ratio,
                        CPL_FRAME_GROUP_PRODUCT,
                        CPL_FRAME_TYPE_IMAGE,
                        CPL_FRAME_LEVEL_INTERMEDIATE,
                        product_filename,
                        UVES_RATIO_TFLAT(chip),
                        raw_headers[raw_index][0],
                        product_header[raw_index],
                        NULL,
                        parameters,
                        recipe_id,
                        PACKAGE "/" PACKAGE_VERSION,
                        qclog,
                        starttime, false, 
                        UVES_ALL_STATS),
               "Could not add ratio image '%s' to frameset", product_filename);

            uves_msg("Master flat ratio '%s' added to frameset", product_filename);
        }


      if(strcmp(PROCESS_CHIP,"REDL") == 0) {
	chip = uves_chip_get_next(chip);
      }

    
    } /* For each chip */
    
  cleanup:
    /* Input */
    if (raw_images[0] != NULL)
    {
        int i;
        for (i = 0; i < cpl_imagelist_get_size(raw_images[0]); i++) 
        {
            if (raw_headers[0] != NULL) uves_free_propertylist(&raw_headers[0][i]);
            if (raw_headers[1] != NULL) uves_free_propertylist(&raw_headers[1][i]);
        }
        cpl_free(raw_headers[0]); raw_headers[0] = NULL;
        cpl_free(raw_headers[1]); raw_headers[1] = NULL;
    }

    uves_free_imagelist(&raw_images[0]);
    uves_free_imagelist(&raw_images[1]);

    /* Master bias */
    uves_free_image(&master_bias);
    uves_free_propertylist(&master_bias_header);

    /* Master dark */
    uves_free_image(&master_dark);
    uves_free_propertylist(&master_dark_header);

    /* Order table */
    uves_free_table(&ordertable);
    uves_free_propertylist(&ordertable_header);
    uves_polynomial_delete(&order_locations);
    uves_free_table(&traces);

    /* Reference master flat */
    uves_free_image(&ref_flat);
    uves_free_propertylist(&ref_flat_header);
    
    /* Output */
    uves_qclog_delete(&qclog[0]);
    uves_free_image(&master_flat);
    uves_free_image(&background);
    uves_free_image(&ratio);
    uves_free_propertylist(&product_header[0]);
    uves_free_propertylist(&product_header[1]);
    cpl_free(product_filename);
    
    return;
}


/*----------------------------------------------------------------------------*/
/**
   @brief    Process a single chip
   @param    raw_images    the input images
   @param    qclog         QC parameters are written here
*/
/*----------------------------------------------------------------------------*/

static void
uves_mflat_qclog(const cpl_imagelist* raw_images,
         cpl_table* qclog)
{
  int nraw=0;

  check_nomsg(uves_qclog_add_string(qclog,
                        "QC TEST1 ID",
                        "Test-on-Master-Flat",
                        "Name of QC test",
                        "%s"));
  check_nomsg(nraw=cpl_imagelist_get_size(raw_images));

  check_nomsg(uves_qclog_add_int(qclog,
                        "PRO DATANCOM",
                        nraw,
                        "Number of frames combined",
                        "%d"));
 cleanup:
  return;
}
/**@}*/
