/*                                                                              *
 *   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 02110-1301 USA          *
 */
 
/*
 * $Author: amodigli $
 * $Date: 2011-01-03 08:39:09 $
 * $Revision: 1.53 $
 * $Name: not supported by cvs2svn $
 *
 */

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

/*----------------------------------------------------------------------------*/
/**
 * @defgroup uves_mdark  Recipe: Master Dark
 *
 * This recipe calculates the master dark frame.
 * See man-page for details.
 */
/*----------------------------------------------------------------------------*/

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

#include <uves_parameters.h>
#include <uves_utils.h>
#include <uves.h>
#include <uves_dfs.h>
#include <uves_pfits.h>
#include <uves_qclog.h>
#include <uves_recipe.h>
#include <uves_utils_wrappers.h>
#include <uves_error.h>
#include <uves_globals.h>

#include <cpl.h>
#include <float.h>
#include <string.h>
/*-----------------------------------------------------------------------------
                            Functions prototypes
 -----------------------------------------------------------------------------*/
/*
static int
uves_qcdark_define_parameters_body(cpl_parameterlist *parameters, 
				   const char *recipe_id);
*/
static int
uves_mdark_define_parameters(cpl_parameterlist *parameters);

static void uves_mdark_region_qc(cpl_image* img, 
                                 const cpl_parameterlist* p,
                                 const cpl_imagelist* raw_images,
				 const char* recipe_id,
                                 cpl_table* qclog);
static cpl_image *
uves_mdark_process_chip(const cpl_imagelist *raw_images, 
			uves_propertylist **raw_headers,
			const cpl_image *master_bias,
			uves_propertylist *mdark_header, 
			const cpl_parameterlist *parameters,
			const char* recipe_id,
                        cpl_table* qclog, const int do_qc);


/*-----------------------------------------------------------------------------
                            Recipe standard code
 -----------------------------------------------------------------------------*/
#define cpl_plugin_get_info uves_mdark_get_info
UVES_RECIPE_DEFINE(
    UVES_MDARK_ID, UVES_MDARK_DOM, 
    /* Warning: if more parameters are added to this recipe, they 
       need to be propagated to uves_cal_mkmaster! */
    uves_mdark_define_parameters,
    "Jonas M. Larsen", "cpl@eso.org",
    "Creates the master dark frame",
    "This recipe creates a master dark frame by taking the median of all\n"
    "input frames which should have identical exposure times. Symbolically,\n"
    "   masterdark = median( dark_i ) - masterbias\n"
    "\n"
    "The input dark frames must have same tag and size and must be either\n"
    "(P)DARK_BLUE or (P)DARK_RED. Also, a master bias (MASTER_BIAS_xxxx) must\n"
    "be provided for each chip (xxxx = BLUE, REDL, REDU).\n"
    "\n"
    "On blue input the recipe computes one master dark frame; on red input the\n"
    "recipe produces a master dark frame for each chip (MASTER_(P)DARK_xxxx).\n");

/**@{*/
/*-----------------------------------------------------------------------------
                            Functions code
 -----------------------------------------------------------------------------*/



/*----------------------------------------------------------------------------*/
/**
  @brief    Find basic parameters to control QC   
  @param    parameters        the parameterlist to fill
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
static cpl_error_code
uves_extract_basic_parameters_for_qc(const cpl_parameterlist* p,
                                     const char* recipe_id,
                                     int * pr_num_x, 
                                     int* pr_num_y, 
                                     int* pr_box_sx, 
                                     int* pr_box_sy)
{

  char name[MAX_NAME_SIZE];
  char pname[MAX_NAME_SIZE];

  sprintf(name,"reg.num_x");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  uves_msg("pname=%s",pname);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,pr_num_x), 
	"Could not read parameter");

  sprintf(name,"reg.num_y");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,pr_num_y), 
	 "Could not read parameter");

  sprintf(name,"reg.box_sx");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,pr_box_sx),
	 "Could not read parameter");

  sprintf(name,"reg.box_sy");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,pr_box_sy),
	 "Could not read parameter");

  cleanup:
  return cpl_error_get_code();

}






/*----------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options    
  @param    parameters        the parameterlist to fill
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
static int
uves_mdark_define_parameters(cpl_parameterlist *parameters)
{
  if (uves_master_stack_define_parameters(parameters,
                                           make_str(UVES_MDARK_ID))
        != CPL_ERROR_NONE)
        {
            return -1;
        }

    return uves_qcdark_define_parameters_body(parameters, 
                         make_str(UVES_MDARK_ID));
}

/*----------------------------------------------------------------------------*/
/**
  @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_qcdark_define_parameters_body(cpl_parameterlist *parameters, 
                  const char *recipe_id)
{
    /*****************
     *    General    *
     *****************/
    if (uves_define_global_parameters(parameters) != CPL_ERROR_NONE)
    {
        return -1;
    }

    if (uves_master_stack_define_parameters(parameters,recipe_id) 
        != CPL_ERROR_NONE)
        {
            return -1;
        }

    
    /****************************
     *  Spline back.sub.        *
     ****************************/
    
    if (uves_propagate_parameters_step(UVES_QCDARK_ID, parameters, 
                       recipe_id, NULL) != 0)
    {
        return -1;
    }

    return (cpl_error_get_code() != CPL_ERROR_NONE);
}



/*----------------------------------------------------------------------------*/
/**
   @brief    Define recipe parameters used for master dark generation
   @param   parameters recipe input parameters
   @return   The parameters for this step

   The parameters defined set region where perform QC
   See source code or 'esorex --man-page' for a description of each parameter.
*/
/*----------------------------------------------------------------------------*/
cpl_error_code 
uves_mdark_define_qc_parameters(cpl_parameterlist* parameters)
{
  


    

    {
   
      const char* name = "reg.num_x";
      char* full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID, name);
      cpl_parameter *p = NULL;
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "Number of regions along the X axis "
                               "(where mean/med/rms are computed). ",
			       UVES_QCDARK_ID,
			       4,0,INT_MAX);

      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name );
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);



      name = "reg.num_y";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "Number of regions along the Y axis"
                               "(where mean/med/rms are computed). ",
			       UVES_QCDARK_ID,
			       4,0,INT_MAX);

      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);



      name = "reg.box_sx";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "Region X size [pix]",
			       UVES_QCDARK_ID,
			       100,0,INT_MAX);
      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);


      name = "reg.box_sy";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "Region Y size [pix]",
			       UVES_QCDARK_ID,
			       100,0,INT_MAX);
      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);

      name = "reg.border_x";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "X distance between the left hand side "
                               "of the detector and the left hand side "
                               "of the region [pix]",
			       UVES_QCDARK_ID,
			       100,0,INT_MAX);
      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);


      name = "reg.border_y";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_range(p, full_name,
			       CPL_TYPE_INT,
			       "X distance between the left hand side "
                               "of the detector and the left hand side "
                               "of the region [pix]",
			       UVES_QCDARK_ID,
			       100,0,INT_MAX);
      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);



      name = "reg.when";
      full_name = uves_sprintf("%s.%s", UVES_QCDARK_ID,name);
      uves_parameter_new_enum(p, full_name,
			       CPL_TYPE_INT,
			       "When QC analysis is performed. "
                               "0: on each raw frame or "
                               "1: on the master frame",
			       UVES_QCDARK_ID,
			      0,2,0,1);
      cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
      cpl_parameterlist_append(parameters, p);
      cpl_free(full_name);


    }
    
    if (cpl_error_get_code() != CPL_ERROR_NONE)
    {
        cpl_msg_error(__func__, "Creation of mdark parameters failed: '%s'", 
              cpl_error_get_where());
        cpl_parameterlist_delete(parameters);
    }
    return cpl_error_get_code();
}


/*----------------------------------------------------------------------------*/
/**
   @brief    Define recipe parameters used for master dark generation
   @return   The parameters for this step

   The parameters defined set region where perform QC
   See source code or 'esorex --man-page' for a description of each parameter.
*/
/*----------------------------------------------------------------------------*/
cpl_parameterlist *
uves_qcdark_define_parameters(void)
{
  
    cpl_parameterlist *parameters = NULL;
    
    parameters = cpl_parameterlist_new();

    check(uves_mdark_define_qc_parameters(parameters),
          "Error defining mdark qc parameters");


  cleanup:  
    if (cpl_error_get_code() != CPL_ERROR_NONE)
    {
        cpl_msg_error(__func__, "Creation of mdark parameters failed: '%s'", 
              cpl_error_get_where());
        cpl_parameterlist_delete(parameters);
        return NULL;
    } else {
       return parameters;
    }
}





/*----------------------------------------------------------------------------*/
/**
  @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_bias The master bias image for this chip, or NULL
  @param    mdark_header The product header. This is updated to contain the exposure time.
  @param    parameters  the parameters list
  @return   The master dark image
 
  This function
  - subtracts from each input image the provided @em master bias (only if provided),
  - computes the master dark image by taking the pixel-by-pixel median of all input frames,

  masterdark = median( (dark_i - masterbias) )

  Note that the master dark frame is not normalized to 1 sec exposure time.

 */
/*----------------------------------------------------------------------------*/
static cpl_image *
uves_mdark_process_chip(const cpl_imagelist *raw_images, 
                        uves_propertylist **raw_headers, 
                        const cpl_image *master_bias,
		        uves_propertylist *mdark_header, 
			const cpl_parameterlist *parameters,
			const char* recipe_id,
			cpl_table* qclog,const int do_qc)
{
   cpl_image *master_dark        = NULL; /* Result */
   cpl_image *current_dark       = NULL;
   cpl_imagelist *preproc_images = NULL;
   double min_exptime = 0;
   double max_exptime = 0;
   int i;
   //char name[MAX_NAME_SIZE];
   //char pname[MAX_NAME_SIZE];

   int pr_num_x=4;
   int pr_num_y=4;
   int pr_box_sx=100;
   int pr_box_sy=100;
   const char* STACK_METHOD=NULL;
   double STACK_KLOW=0;
   double STACK_KHIGH=0;
   int STACK_NITER=0;

/* check critical QC parameters to see if QC need to be computed or not */

   check_nomsg(uves_extract_basic_parameters_for_qc(parameters,recipe_id,
                                                    &pr_num_x,&pr_num_y, 
                                                    &pr_box_sx,&pr_box_sy));

/* parameters for stacking */
    check( uves_get_parameter(parameters, NULL, recipe_id, "stack_method", CPL_TYPE_STRING, &STACK_METHOD),
               "Could not read parameter");

    uves_string_toupper((char*)STACK_METHOD);

    check( uves_get_parameter(parameters, NULL, recipe_id, "klow", CPL_TYPE_DOUBLE, &STACK_KLOW),
               "Could not read parameter");
    check( uves_get_parameter(parameters, NULL, recipe_id, "khigh", CPL_TYPE_DOUBLE, &STACK_KHIGH),
               "Could not read parameter");
    check( uves_get_parameter(parameters, NULL, recipe_id, "niter", CPL_TYPE_INT, &STACK_NITER),
               "Could not read parameter");



    /* First process each input image and store the results in a 
       new image list */

    preproc_images = cpl_imagelist_new();
    for (i = 0; i < cpl_imagelist_get_size(raw_images); i++)
    {
        double exposure_time = 0.0;
        const uves_propertylist *current_header;
        
        current_dark = 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_dark, master_bias), 
               "Error subtracting master bias");

                    if (false) {
            uves_msg_debug("Thresholding to non-negative values");
            check( cpl_image_threshold(current_dark, 
                           0, DBL_MAX,     /* Interval */
                           0, DBL_MAX),    /* New values */
               "Error thresholding image");
                    }
        }
        else
        {
            uves_msg("Skipping bias subtraction");
        }
        
         check( exposure_time = uves_pfits_get_exptime(current_header),
           "Error reading exposure time");

        if(pr_num_x != 0 && pr_num_y != 0 && pr_box_sx != 0 && pr_box_sy !=0 ) {
        if(do_qc == 0) {
	  uves_msg("Calculating QC parameters on raw dark frame %d",i);
          uves_mdark_region_qc(current_dark,parameters,raw_images,recipe_id,qclog);
	}

        }
        /* Initialize/update min/max exposure time*/
        if (i == 0 || exposure_time < min_exptime)
        {
            min_exptime = exposure_time;
        }
        if (i == 0 || exposure_time > max_exptime)
        {
            max_exptime = exposure_time;
        }

        /* Do not normalize to unit exposure time */
/*        If this is uncommented, then remember to also calculate the
        correct master dark exposure time below.
            uves_msg("Normalizing from %f s to unit exposure time", exposure_time);
        check( cpl_image_divide_scalar(current_dark, exposure_time), 
        "Error normalizing dark frame");   */        

        /* Append to imagelist */
        check( cpl_imagelist_set(preproc_images,
                     current_dark,  
                     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_dark = NULL;
    }

    /* Check exposure times */
    uves_msg("Exposure times range from %e s to %e s (%e %% variation)", 
            min_exptime,
            max_exptime,
            100 * (max_exptime - min_exptime) / min_exptime);

    if ((max_exptime - min_exptime) / min_exptime > .001)
    {
        uves_msg_warning("Exposure times differ by %e %%", 
                 100 * (max_exptime - min_exptime) / min_exptime);
    }
    
    /* Get median stack of input darks */
    if(strcmp(STACK_METHOD,"MEDIAN")==0) {
       uves_msg("Calculating stack median");
       check( master_dark = cpl_imagelist_collapse_median_create(preproc_images), 
              "Error computing median");
    } else {
       uves_msg("Calculating stack mean");
       check( master_dark = uves_ksigma_stack(preproc_images,STACK_KLOW,
                                              STACK_KHIGH,STACK_NITER),
              "Error computing master dark");

    } 
    check( uves_pfits_set_exptime(mdark_header, (max_exptime + min_exptime)/2),
       "Error setting master dark exposure time");
    //uves_pfits_set_extname(mdark_header,"Master dark");
    
  cleanup:
    uves_free_image(&current_dark);
    uves_free_imagelist(&preproc_images);
    if (cpl_error_get_code() != CPL_ERROR_NONE)
    {
        uves_free_image(&master_dark);
    }
    
    return master_dark;
}


/*----------------------------------------------------------------------------*/
/**
  @brief    Executor function
  @param    parameters  the parameters list
  @param    frames      the frames list
  @param    starttime   execution start
 */
/*----------------------------------------------------------------------------*/
static void
UVES_CONCAT2X(UVES_MDARK_ID,exe)(cpl_frameset *frames, 
                   const cpl_parameterlist *parameters,
                   const char *starttime)
{
    uves_mdark_exe_body(frames, parameters, starttime, make_str(UVES_MDARK_ID));
    return;
}

/*----------------------------------------------------------------------------*/
/**
  @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 dark frame, the pixel average, standard deviation
  and median values are also computed and written in appropriate keywords in the
  output image header.

 */
/*----------------------------------------------------------------------------*/
void
uves_mdark_exe_body(cpl_frameset *frames, 
            const cpl_parameterlist *parameters,
            const char *starttime,
            const char *recipe_id)
{
    /* Function id */
    /*
     * Variables that will contain the values of the recipe parameters 
     */
    /* None */

    /* CPL objects */
    /* Input */
    cpl_imagelist *raw_images[2]       = {NULL, NULL};
    uves_propertylist  **raw_headers[2] = {NULL, NULL};    /* Two arrays of pointers */

    /* Master bias */
    cpl_image *master_bias               = NULL;
    uves_propertylist *master_bias_header = NULL;
    
    /* Output */
    cpl_table* qclog[2] = {NULL, NULL};
    cpl_image *master_dark              = NULL;
    uves_propertylist *product_header[2] = {NULL, NULL};
    
    /* Local variables */
    char *product_filename = NULL;
    const char *product_tag[2] = {NULL, NULL};
    bool blue;
    enum uves_chip chip;

    const char* pname=NULL;
   

    int pr_when=0;
    const char* PROCESS_CHIP=NULL;
    int pr_num_x=0;
    int pr_num_y=0;
    int pr_box_sx=0;
    int pr_box_sy=0;
    bool dump_qc=true;

    /* Load and check raw dark images and headers, identify arm (blue/red) */
    /* On success, 'raw_headers' will be an array with the same size as 'raw_images' */
    if (cpl_frameset_find(frames, UVES_DARK(true )) != NULL ||
    cpl_frameset_find(frames, UVES_DARK(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       false,    /* FLAMES format? */
                       UVES_DARK(true), UVES_DARK(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw dark 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_DARK(chip);
        }
    }
    else if (cpl_frameset_find(frames, UVES_PDARK(true )) != NULL ||
         cpl_frameset_find(frames, UVES_PDARK(false)) != NULL)
    {
        check( uves_load_raw_imagelist(frames, 
                       false,  /* FLAMES format? */
                       UVES_PDARK(true), UVES_PDARK(false),
                       CPL_TYPE_DOUBLE,
                       raw_images, raw_headers, product_header, 
                       &blue), "Error loading raw dark 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_PDARK(chip);
        }
    }
    else
    {
        assure(false, CPL_ERROR_DATA_NOT_FOUND,
           "Missing input dark frame: %s, %s, %s or %s expected",
           UVES_DARK(true) , UVES_DARK(false),
           UVES_PDARK(true), UVES_PDARK(false));
    }


  
   check_nomsg(uves_extract_basic_parameters_for_qc(parameters,recipe_id,
                                                    &pr_num_x,&pr_num_y, 
                                                    &pr_box_sx,&pr_box_sy));

   if(pr_num_x <=0 || pr_num_y <= 0 || pr_box_sx <=0 || pr_box_sy <= 0) {
      dump_qc=false;
   }
    pname = uves_sprintf("%s.%s", UVES_QCDARK_ID, "reg.when");
    check(uves_get_parameter(parameters,NULL,recipe_id,pname,CPL_TYPE_INT,&pr_when), 
	 "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);


    /* 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);
      }

        const char *master_bias_filename = "";
        const char *chip_name = "";
        
        int raw_index = uves_chip_get_index(chip);
        
        uves_msg("Processing %s chip",
             uves_chip_tostring_upper(chip));

        /* Get 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)
        {
            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");
        }
        
        /* Process chip */



        uves_free_image(&master_dark);
	uves_qclog_delete(&qclog[0]);
	qclog[0] = uves_qclog_init(raw_headers[raw_index][0], chip);
        check( master_dark = uves_mdark_process_chip(raw_images[raw_index], 
						     raw_headers[raw_index], 
						     master_bias,
						     product_header[raw_index],
						     parameters,recipe_id,
                                                     qclog[0],pr_when),
	       "Error processing chip");


        /* Finished. Save */
                /* Finished. Calculate QC parameters and save */
        if(pr_when==1) {
	  uves_msg("Calculating QC parameters on master dark frame");
          uves_mdark_region_qc(master_dark,parameters,
		  	       raw_images[raw_index],recipe_id,qclog[0]);

	}

        /* Insert into frame set */
        uves_msg("Saving product");
        
        cpl_free(product_filename);
        check( product_filename = uves_masterdark_filename(chip), "Error getting filename");

  
        check( uves_frameset_insert(frames,
                    master_dark,
                    CPL_FRAME_GROUP_PRODUCT,
                    CPL_FRAME_TYPE_IMAGE,
                    CPL_FRAME_LEVEL_INTERMEDIATE,
                    product_filename,
                    product_tag[raw_index],
                    raw_headers[raw_index][0],
                    product_header[raw_index],
                    NULL,
                    parameters,
                    recipe_id,
                    PACKAGE "/" PACKAGE_VERSION,qclog,
                    starttime, dump_qc, 
                    UVES_ALL_STATS), 
           "Could not add master dark %s to frameset", product_filename);
        uves_msg("Master dark %s added to frameset", product_filename);
        uves_qclog_delete(&qclog[0]);

      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);

    /* Output */
    uves_qclog_delete(&qclog[0]);
    uves_free_image(&master_dark);
    uves_free_propertylist(&product_header[0]);
    uves_free_propertylist(&product_header[1]);
    cpl_free(product_filename);
    uves_free(pname);
    return;
}


static void 
uves_mdark_region_qc(cpl_image* img, 
                     const cpl_parameterlist* p,
                     const cpl_imagelist* raw_images,
                     const char* recipe_id,
                     cpl_table* qclog)
{

  int pr_num_x=4;
  int pr_num_y=4;
  int pr_box_sx=100;
  int pr_box_sy=100;
  int pr_border_x=100;
  int pr_border_y=100;


  int i=0;
  int j=0;
  int llx=0;
  int lly=0;
  int urx=0;
  int ury=0;
  int space_x=0;
  int space_y=0;
  int sx=0;
  int sy=0;
  int nraw=0;
  int raw=0;
  char name[MAX_NAME_SIZE];
  char pname[MAX_NAME_SIZE];
  char qc_key[MAX_NAME_SIZE];
  char qc_com[MAX_NAME_SIZE];
  double qc_avg=0;
  double qc_med=0;
  double qc_rms=0;
  double qc_min=0;
  double qc_max=0;
  cpl_table* qc_sto=NULL;
 
  check_nomsg(uves_extract_basic_parameters_for_qc(p,recipe_id,
                                                    &pr_num_x,&pr_num_y, 
                                                    &pr_box_sx,&pr_box_sy));

  uves_msg("pr_num_x=%d pr_num_y=%d pr_box_sx=%d pr_box_sy=%d",
          pr_num_x,pr_num_y,pr_box_sx,pr_box_sy);

  if(pr_num_x <= 0 || pr_num_y <= 0 || pr_box_sx <= 0 || pr_box_sy <= 0) {
     return; 
  }
 
  sprintf(name,"reg.border_x");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,&pr_border_x),
	 "Could not read parameter");

  sprintf(name,"reg.border_y");
  sprintf(pname,"%s.%s", UVES_QCDARK_ID, name);
  check(uves_get_parameter(p,NULL,recipe_id,pname,CPL_TYPE_INT,&pr_border_y),
	 "Could not read parameter");


  check_nomsg(nraw=cpl_imagelist_get_size(raw_images));
  check_nomsg(uves_qclog_add_int(qclog,
                        "PRO DATANCOM",
                        nraw,
                        "Number of frames combined",
                        "%d"));

  sx=cpl_image_get_size_x(img);
  sy=cpl_image_get_size_y(img);
  space_x=(int)((sx-2*pr_border_x)/pr_num_x);
  space_y=(int)((sy-2*pr_border_y)/pr_num_y);
  qc_sto=cpl_table_new(pr_num_x*pr_num_y);
  cpl_table_new_column(qc_sto,"MIN",CPL_TYPE_DOUBLE);
  cpl_table_new_column(qc_sto,"MAX",CPL_TYPE_DOUBLE);
  cpl_table_new_column(qc_sto,"AVG",CPL_TYPE_DOUBLE);
  cpl_table_new_column(qc_sto,"MED",CPL_TYPE_DOUBLE);
  cpl_table_new_column(qc_sto,"RMS",CPL_TYPE_DOUBLE);

  for(i=0;i<pr_num_x;i++) {
    llx=pr_border_x+i*space_x;
    urx=llx+pr_box_sx;

    llx=(llx>0) ? llx:1;
    urx=(urx<=sx) ? urx:sx;

    for(j=0;j<pr_num_y;j++) {
      lly=pr_border_y+j*space_y;
      ury=lly+pr_box_sy;

      lly=(lly>0) ? lly:1;
      ury=(ury<=sy) ? ury:sy;

      raw=i*pr_num_y+j;
      check_nomsg(qc_min=cpl_image_get_min_window(img,llx,lly,urx,ury));
      qc_max=cpl_image_get_min_window(img,llx,lly,urx,ury);
      qc_avg=cpl_image_get_mean_window(img,llx,lly,urx,ury);
      qc_med=cpl_image_get_median_window(img,llx,lly,urx,ury);
      qc_rms=cpl_image_get_stdev_window(img,llx,lly,urx,ury);
      uves_msg_debug("QC on area [%d,%d:%d,%d]. Min %g Max %g Avg %g Med %g Rms %g",
	       llx,lly,urx,ury,qc_min,qc_max,qc_avg,qc_med,qc_rms);

      sprintf(qc_key,"%s%d%d%s","QC REG",i,j," MIN");
      sprintf(qc_com,"%s%d%d","Min of region [%d,%d]",i,j);
      check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));
      check_nomsg(cpl_table_set_double(qc_sto,"MIN",raw,qc_min));

      sprintf(qc_key,"%s%d%d%s","QC REG",i,j," MAX");
      sprintf(qc_com,"%s%d%d","Max of region [%d,%d]",i,j);
      check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));
      check_nomsg(cpl_table_set_double(qc_sto,"MAX",raw,qc_max));

      sprintf(qc_key,"%s%d%d%s","QC REG",i,j," AVG");
      sprintf(qc_com,"%s%d%d","Mean of region [%d,%d]",i,j);
      check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));
      check_nomsg(cpl_table_set_double(qc_sto,"AVG",raw,qc_avg));

      sprintf(qc_key,"%s%d%d%s","QC REG",i,j," MED");
      sprintf(qc_com,"%s%d%d","Median of region [%d,%d]",i,j);
      check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));
      check_nomsg(cpl_table_set_double(qc_sto,"MED",raw,qc_med));

      sprintf(qc_key,"%s%d%d%s","QC REG",i,j," RMS");
      sprintf(qc_com,"%s%d%d","Rms of region [%d,%d]",i,j);
      check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));
      check_nomsg(cpl_table_set_double(qc_sto,"RMS",raw,qc_rms));


    }
  }


  check_nomsg(qc_min=cpl_table_get_column_min(qc_sto,"MIN"));
  check_nomsg(qc_max=cpl_table_get_column_max(qc_sto,"MIN"));
  check_nomsg(qc_avg=cpl_table_get_column_mean(qc_sto,"MIN"));
  check_nomsg(qc_med=cpl_table_get_column_median(qc_sto,"MIN"));
  check_nomsg(qc_rms=cpl_table_get_column_stdev(qc_sto,"MIN"));

  sprintf(qc_key,"%s","QC REG MIN MIN");
  sprintf(qc_com,"%s","Min of all Mins");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MIN MAX");
  sprintf(qc_com,"%s","Max of all Mins");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MIN AVG");
  sprintf(qc_com,"%s","Mean of all Mins");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MIN MED");
  sprintf(qc_com,"%s","Median of all Mins");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MIN RMS");
  sprintf(qc_com,"%s","Rms of all Mins");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));



  check_nomsg(qc_min=cpl_table_get_column_min(qc_sto,"MAX"));
  check_nomsg(qc_max=cpl_table_get_column_max(qc_sto,"MAX"));
  check_nomsg(qc_avg=cpl_table_get_column_mean(qc_sto,"MAX"));
  check_nomsg(qc_med=cpl_table_get_column_median(qc_sto,"MAX"));
  check_nomsg(qc_rms=cpl_table_get_column_stdev(qc_sto,"MAX"));

  sprintf(qc_key,"%s","QC REG MAX MIN");
  sprintf(qc_com,"%s","Min of all Maxs");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MAX MAX");
  sprintf(qc_com,"%s","Max of all Maxs");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MAX AVG");
  sprintf(qc_com,"%s","Mean of all Maxs");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MAX MED");
  sprintf(qc_com,"%s","Median of all Maxs");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MAX RMS");
  sprintf(qc_com,"%s","Rms of all Maxs");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));


  check_nomsg(qc_min=cpl_table_get_column_min(qc_sto,"AVG"));
  check_nomsg(qc_max=cpl_table_get_column_max(qc_sto,"AVG"));
  check_nomsg(qc_avg=cpl_table_get_column_mean(qc_sto,"AVG"));
  check_nomsg(qc_med=cpl_table_get_column_median(qc_sto,"AVG"));
  check_nomsg(qc_rms=cpl_table_get_column_stdev(qc_sto,"AVG"));

  sprintf(qc_key,"%s","QC REG AVG MIN");
  sprintf(qc_com,"%s","Min of all Means");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG AVG MAX");
  sprintf(qc_com,"%s","Max of all Means");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG AVG AVG");
  sprintf(qc_com,"%s","Mean of all Means");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG AVG MED");
  sprintf(qc_com,"%s","Median of all Means");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG AVG RMS");
  sprintf(qc_com,"%s","Rms of all Means");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));


  check_nomsg(qc_min=cpl_table_get_column_min(qc_sto,"MED"));
  check_nomsg(qc_max=cpl_table_get_column_max(qc_sto,"MED"));
  check_nomsg(qc_avg=cpl_table_get_column_mean(qc_sto,"MED"));
  check_nomsg(qc_med=cpl_table_get_column_median(qc_sto,"MED"));
  check_nomsg(qc_rms=cpl_table_get_column_stdev(qc_sto,"MED"));

  sprintf(qc_key,"%s","QC REG MED MIN");
  sprintf(qc_com,"%s","Min of all Medians");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MED MAX");
  sprintf(qc_com,"%s","Max of all Medians");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MED AVG");
  sprintf(qc_com,"%s","Mean of all Medians");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MED MED");
  sprintf(qc_com,"%s","Median of all Medians");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG MED RMS");
  sprintf(qc_com,"%s","Rms of all Medians");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));


  check_nomsg(qc_min=cpl_table_get_column_min(qc_sto,"RMS"));
  check_nomsg(qc_max=cpl_table_get_column_max(qc_sto,"RMS"));
  check_nomsg(qc_avg=cpl_table_get_column_mean(qc_sto,"RMS"));
  check_nomsg(qc_med=cpl_table_get_column_median(qc_sto,"RMS"));
  check_nomsg(qc_rms=cpl_table_get_column_stdev(qc_sto,"RMS"));


  sprintf(qc_key,"%s","QC REG RMS MIN");
  sprintf(qc_com,"%s","Min of all Rms");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_min,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG RMS MAX");
  sprintf(qc_com,"%s","Max of all Rms");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_max,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG RMS AVG");
  sprintf(qc_com,"%s","Mean of all Rms");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_avg,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG RMS MED");
  sprintf(qc_com,"%s","Median of all Rms");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_med,qc_com,"%g"));

  sprintf(qc_key,"%s","QC REG RMS RMS");
  sprintf(qc_com,"%s","Rms of all Rms");
  check_nomsg(uves_qclog_add_double(qclog,qc_key,qc_rms,qc_com,"%g"));




 cleanup:
  uves_free_table(&qc_sto);

  return;

}


/**@}*/
