/*                                                                              *
 *   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.12 $
 */

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

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



/*-----------------------------------------------------------------------------
                                Includes
 -----------------------------------------------------------------------------*/
#include <uves_reduce_mflat_combine.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_reduce_mflat_combine(cpl_frameset *frames, 
                          const cpl_parameterlist *parameters,
                          bool flames,
                          const char *recipe_id, 
                          const char *starttime);

/*-----------------------------------------------------------------------------
                            Implementation
 -----------------------------------------------------------------------------*/
const char * const uves_mflat_combine_desc =
"This recipe combined a MASTER_FLAT_xxxx with a MASTER_DFLAT_xxxx\n"
"Input are:\n" 
"a master flat (MASTER_FLAT_xxxx)\n"
"a master dflat (MASTER_DFLAT_xxxx)\n"
"an order table (ORDER_TABLE_xxxx)\n"
"provided for each chip (xxxx = BLUE, REDL, REDU). \n"
"Output is a MASTER_FLAT_xxxx\n";

/*----------------------------------------------------------------------------*/
/**
  @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_combine_define_parameters_body(cpl_parameterlist *parameters, 
                  const char *recipe_id)
{

    /*****************
    *    General    *
    *****************/
   if (uves_define_global_parameters(parameters) != CPL_ERROR_NONE)
   {
      return -1;
   }

    return (cpl_error_get_code() != CPL_ERROR_NONE);
}




/*----------------------------------------------------------------------------*/
/**
   @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_combine_exe_body(cpl_frameset *frames, 
                            const cpl_parameterlist *parameters,
                            const char *starttime,
                            const char *recipe_id)
{
   bool flames = false;
   check_nomsg(uves_reduce_mflat_combine(frames, parameters,flames,recipe_id,
                                   starttime));
    
  cleanup:
   return;
}

/*----------------------------------------------------------------------------*/
/**
   @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.

*/



cpl_image*
uves_combine_flats(const cpl_frame* frm_flat,
                   const cpl_frame* frm_dflat,
                   cpl_frameset* frames,
                   bool flames,
 const int ORDER_THRESHOLD)
{


   const char                *   name_flat=NULL ;
   const char                *   name_dflat=NULL ;
   const char *ordertable_filename = "";

   cpl_image*              ima_flat=NULL;
   cpl_image*              ima_dflat=NULL;
   cpl_image*              ima_cflat=NULL;
   cpl_image*              ima_mask=NULL;

   int sx=0;
   int sy=0;
   int j=0;
   int i=0;
 
   double* point_mask=NULL;

   double xpos=0;
   double ypos=0;
  
   double order_ref=(double)ORDER_THRESHOLD;
   int ypos_min=0;
   int ypos_max=0;
   int ypos_cen=0;
   int xpos_cen=0;
   int xrad=5;
   int yrad=5;
   int llx=0;
   int lly=0;
   int urx=0;
   int ury=0;
   double dflux=0;
   double fflux=0;
   double scale=0;

   /* Input */
   /* Order table */
   cpl_table        *ordertable            = NULL;
   uves_propertylist *ordertable_header     = NULL;
   polynomial       *order_locations       = NULL;
   cpl_table        *traces                = NULL;
  const char *chip_name = "";
  enum uves_chip chip=UVES_CHIP_BLUE;

 
 
   name_flat=cpl_frame_get_filename(frm_flat);
   name_dflat=cpl_frame_get_filename(frm_dflat);
   check_nomsg(ima_flat=cpl_image_load(name_flat,CPL_TYPE_DOUBLE,0,0));
   check_nomsg(ima_dflat=cpl_image_load(name_dflat,CPL_TYPE_DOUBLE,0,0));

   /* check size flat is same as size dflat */
   sx=cpl_image_get_size_x(ima_flat);
   sy=cpl_image_get_size_y(ima_flat);
   assure(sx==cpl_image_get_size_x(ima_dflat),CPL_ERROR_ILLEGAL_INPUT,
          "illagal x size");
   assure(sy==cpl_image_get_size_y(ima_dflat),CPL_ERROR_ILLEGAL_INPUT,
          "illagal y size");


 
   check_nomsg( chip_name = UVES_CHIP_ID(chip));
   uves_msg("Combining %s chip", uves_chip_tostring_upper(chip));
   
   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);

   /* Do real job */
   ypos=uves_polynomial_evaluate_2d(order_locations,0,order_ref);
   ypos+=uves_polynomial_evaluate_2d(order_locations,0,order_ref+1);
   ypos/=2.;
   ypos_min=(int)ypos;


   ypos=uves_polynomial_evaluate_2d(order_locations,(double)sx,order_ref);
   ypos+=uves_polynomial_evaluate_2d(order_locations,(double)sx,order_ref+1);
   ypos/=2.;
   ypos_max=(int)ypos;
 
   uves_msg_debug("ypos min=%d max=%d",ypos_min,ypos_max);
   ima_mask = cpl_image_new(sx,sy,CPL_TYPE_DOUBLE);
   point_mask=cpl_image_get_data_double(ima_mask);
   /* set upper part of mask to 1 */
   for(j=(int)ypos_max;j<sy;j++) {
      for(i=0;i<sx;i++) {
         point_mask[j*sx+i]=1.;
      }
   }

   /* in transition region (only) make the check */
   for(j=ypos_min;j<ypos_max;j++) {
      for(i=0;i<sx;i++) {
         xpos=(double)i;
         /* Here the order trace pass through the order center 
            but we want to have the trace in the inter order region
            y=(yc1+yc2)/2; where yc1 and yc2 are the two position at 
                           order center and order+1 center
         */ 
         ypos= uves_polynomial_evaluate_2d(order_locations,xpos,order_ref);
         ypos+=uves_polynomial_evaluate_2d(order_locations,xpos,order_ref+1);
         ypos/=2.;
         if(j > ypos)  {
            point_mask[j*sx+i] = 1.;
         }
      }
   }

/*
   cpl_image_save(ima_mask,"ima_mask_ord.fits", CPL_BPP_IEEE_FLOAT,NULL,
                  CPL_IO_DEFAULT);

*/
   /*determine ref flux on flat (order_ref+1) */
   xpos_cen=sx/2;
   llx=xpos_cen-xrad;
   urx=xpos_cen+xrad; 
   ypos= uves_polynomial_evaluate_2d(order_locations,(double)xpos_cen,
                                     order_ref+1);
   ypos_cen=(int)ypos;
   lly=ypos_cen-yrad;
   ury=ypos_cen+yrad;
   fflux=cpl_image_get_median_window(ima_flat,llx,lly,urx,ury);



   /*determine ref flux on dflat (order_ref) */
   ypos=uves_polynomial_evaluate_2d(order_locations,(double)xpos_cen,order_ref);
   ypos_cen=(int)ypos;
   lly=ypos_cen-yrad;
   ury=ypos_cen+yrad;
   dflux=cpl_image_get_median_window(ima_dflat,llx,lly,urx,ury);
 

   scale=fflux/dflux;

   uves_msg_debug("flux: n=%g d=%g s=%g",fflux,dflux,scale);

   /* combine images */
   ima_cflat=cpl_image_duplicate(ima_flat);
   cpl_image_multiply(ima_cflat,ima_mask);
   cpl_image_multiply_scalar(ima_mask,-1.);
   cpl_image_add_scalar(ima_mask,1.);
   cpl_image_multiply(ima_dflat,ima_mask);
   cpl_image_multiply_scalar(ima_dflat,scale);
   cpl_image_add(ima_cflat,ima_dflat);
/*
   cpl_image_save(ima_cflat,"ima_cflat.fits", CPL_BPP_IEEE_FLOAT,NULL,
                  CPL_IO_DEFAULT);
*/


  cleanup:

   uves_free_table(&ordertable);
   uves_free_propertylist(&ordertable_header);
   uves_polynomial_delete(&order_locations);
   uves_free_table(&traces);
   uves_free_image(&ima_flat);
   uves_free_image(&ima_dflat);
   uves_free_image(&ima_mask);

   return ima_cflat;
}
/*----------------------------------------------------------------------------*/
/**
  @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
  @return   CPL_ERROR_NONE if everything is ok
 */
/*----------------------------------------------------------------------------*/
static void
uves_reduce_mflat_combine(cpl_frameset *frames, 
                          const cpl_parameterlist *parameters,
                          bool flames,
                          const char *recipe_id,
                          const char *starttime)
{
   bool debug_mode;
   cpl_frame           *   frm_dflat=NULL ;
   cpl_frame           *   frm_flat=NULL ;
    const char                *   name_flat=NULL ;
   const char                *   name_dflat=NULL ;
   uves_propertylist* hflat=NULL;

   /* Output */
   cpl_table *qclog[]                  = {NULL, NULL};
   uves_propertylist *product_header=NULL;
   cpl_image* ima_cflat=NULL;
 
   /* Local variables */
   //char *product_filename = "master_cflat_blue.fits";
   char *product_filename = NULL;
   const char *product_tag[2] = {NULL, NULL};
   char pro_filename[255];
   //const char *product_tag = "MASTER_FLAT_BLUE";
   const char* PROCESS_CHIP=NULL;
   int ORDER_THRESHOLD=7;

   enum uves_chip chip;
   int raw_index=0;
   bool blue=true;

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

   check( uves_get_parameter(parameters, NULL, "uves", "order_threshold", 
                             CPL_TYPE_INT, &ORDER_THRESHOLD), 
          "Could not read parameter");

   for (chip = uves_chip_get_first(blue); 
        chip != UVES_CHIP_INVALID; 
        chip = uves_chip_get_next(chip))
   {
      if (
        cpl_frameset_find(frames,UVES_MASTER_FLAT(chip)) != NULL || 
        cpl_frameset_find(frames,UVES_MASTER_DFLAT(chip)) != NULL 
         )
      {

         if(chip == UVES_CHIP_BLUE) {
            blue = true;
         }
         else {
            blue = false;
         }
      } else {
            blue = false;
      }
   }
   
   /* Load and check input frames */
   /* 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));

 
      frm_flat=cpl_frameset_find(frames,UVES_MASTER_FLAT(chip));
      frm_dflat=cpl_frameset_find(frames,UVES_MASTER_DFLAT(chip));
 
      if(frm_flat == NULL && frm_dflat == NULL) {
         uves_msg_error("A %s or %s frame or both must be provided in input",
                        UVES_MASTER_FLAT(chip),UVES_MASTER_DFLAT(chip));
         goto cleanup;
      }
      else if(frm_flat == NULL && frm_dflat != NULL) {
         name_dflat=cpl_frame_get_filename(frm_dflat); 
         hflat=uves_propertylist_load(name_dflat,0);
         ima_cflat=cpl_image_load(name_dflat,CPL_TYPE_DOUBLE,0,0);
      } else if (frm_flat != NULL && frm_dflat == NULL) {
         name_flat=cpl_frame_get_filename(frm_flat); 
         hflat=uves_propertylist_load(name_flat,0);
         ima_cflat=cpl_image_load(name_flat,CPL_TYPE_DOUBLE,0,0);
      } else {
         check_nomsg(name_dflat=cpl_frame_get_filename(frm_dflat));
         check_nomsg(hflat=uves_propertylist_load(name_dflat,0));

         check_nomsg(ima_cflat=uves_combine_flats(frm_flat,frm_dflat,frames,
                                                  flames,ORDER_THRESHOLD));
  
      }

      cpl_free(product_filename);
      check( product_filename = uves_masterflat_filename(chip),
            "Error getting filename");


      sprintf(pro_filename,product_filename);
      product_header=uves_propertylist_duplicate(hflat);
      product_tag[uves_chip_get_index(chip)] = UVES_MASTER_FLAT(chip);
   
      check( uves_frameset_insert(
                frames,
                ima_cflat,
                CPL_FRAME_GROUP_PRODUCT,
                CPL_FRAME_TYPE_IMAGE,
                CPL_FRAME_LEVEL_INTERMEDIATE,
                pro_filename,
                product_tag[raw_index],
                hflat,
                product_header,
                NULL,
                parameters,
                recipe_id,
                PACKAGE "/" PACKAGE_VERSION, qclog,
                starttime, true, UVES_ALL_STATS),
             "Could not add master flat %s %s to frameset", 
             pro_filename, product_tag[raw_index]);

      uves_msg("Master flat %s %s added to frameset", 
               pro_filename, product_tag[raw_index]);


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


     uves_free_image(&ima_cflat);
     uves_qclog_delete(&qclog[0]);
     uves_free_propertylist(&product_header);
     uves_free_propertylist(&hflat);
    
   } /* For each chip */
    

  cleanup:
  
  uves_free_image(&ima_cflat);
  uves_qclog_delete(&qclog[0]);
  uves_free_propertylist(&product_header);
  uves_free_propertylist(&hflat);
  cpl_free(product_filename);

   return;
}


/**@}*/
