/*                                                                            *
 *   This file is part of the ESO X-shooter Pipeline                          *
 *   Copyright (C) 2006 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-01-03 15:40:13 $
 * $Revision: 1.100 $
 *
*/

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

/*----------------------------------------------------------------------------*/
/**
 * @defgroup xsh_scired_ifu_offset   xsh_scired_ifu_offset
 * @ingroup recipes
 *
 * This recipe ...
 * See man-page for details.
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*-----------------------------------------------------------------------------
  Includes
  ----------------------------------------------------------------------------*/

/* DRL steps */

/* Error handling */
#include <xsh_error.h>
/* Utility fonctions */
#include <xsh_utils.h>
#include <xsh_msg.h>
/* DFS functions */
#include <xsh_dfs.h>
#include <xsh_pfits.h>
#include <xsh_data_spectrum1D.h>
#include <xsh_model_arm_constants.h>
/* DRL functions */
#include <xsh_drl.h>
#include <xsh_drl_check.h>
/* Library */
#include <cpl.h>
#include <xsh_blaze.h>
#include <xsh_utils_ifu.h>
#include <xsh_utils_image.h>
/*-----------------------------------------------------------------------------
  Defines
  ---------------------------------------------------------------------------*/

#define RECIPE_ID "xsh_scired_ifu_offset_drl"
#define RECIPE_AUTHOR "P.Goldoni, L.Guglielmi, R. Haigron, F. Royer"
#define RECIPE_CONTACT "amodigli@eso.org"

/*-----------------------------------------------------------------------------
  Functions prototypes
  ----------------------------------------------------------------------------*/

/*
 *   Plugin initalization, execute and cleanup handlers
 */

static int xsh_scired_ifu_offset_create( cpl_plugin *);
static int xsh_scired_ifu_offset_exec( cpl_plugin *);
static int xsh_scired_ifu_offset_destroy( cpl_plugin *);

/* The actual executor function */
static void xsh_scired_ifu_offset( cpl_parameterlist *, cpl_frameset *);

/*-----------------------------------------------------------------------------
  Static variables
  ----------------------------------------------------------------------------*/
static char xsh_scired_ifu_offset_description_short[] =
"Reduce science exposure in IFU configuration and on/off mode";

static char xsh_scired_ifu_offset_description[] =
"This recipe reduces science exposure in IFU configuration and on/off mode\n\
Input Frames : \n\
  - A set of 2xn Science frames, \
      Tag = OBJECT_IFU_OFFSET_arm, SKY_IFU_arm\n\
  - A spectral format table (Tag = SPECTRAL_FORMAT_TAB_arm)\n\
  - A master flat frame (Tag = MASTER_FLAT_IFU_arm)\n\
  - An order table frame(Tag = ORDER_TABLE_EDGES_IFU_arm)\n\
  - 3 wave solution frames, one per slitlet (Tag = WAVE_TAB_ARC_IFU_slitlet_arm)\n\
      where 'slitlet' is DOWN, CEN or UP\n\
  - [OPTIONAL] A dispersion table (Tag = DISP_TAB_IFU_arm)\n\
  - [OPTIONAL] A badpixel map (Tag = BADPIXEL_MAP_arm)\n\
Products : \n\
  - 3 Spectrum order tables 2D (1 per slitlet), PRO.CATG=ORDER2D_slitlet_IFU_arm\n\
  - 3 Spectrum order tables 1D (1 per slitlet), PRO.CATG=ORDER1D_slitlet_IFU_arm\n\
  - 3 Spectrum merge tables 2D (1 per slitlet), PRO.CATG=MERGE2D_slitlet_IFU_arm\n\
  - 3 Spectrum merge tables 1D (1 per slitlet), PRO.CATG=MERGE1D_slitlet_IFU_arm\n\
  - 1 Spectrum merge 3D, PRO.CATG=MERGE3D_IFU_arm\n" ;

/*-----------------------------------------------------------------------------
  Functions code
  ----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/**
   @brief    Build the list of available plugins, for this module.
   @param    list    the plugin list
   @return   0 if everything is ok, -1 otherwise

   Create the recipe instance and make it available to the application using the
   interface. This function is exported.
*/
/*----------------------------------------------------------------------------*/

int cpl_plugin_get_info(cpl_pluginlist *list) {
  cpl_recipe *recipe = NULL;
  cpl_plugin *plugin = NULL;

  recipe = cpl_calloc(1, sizeof(*recipe));
  if ( recipe == NULL ){
    return -1;
  }

  plugin = &recipe->interface ;

  cpl_plugin_init(plugin,
                  CPL_PLUGIN_API,                    /* Plugin API */
                  XSH_BINARY_VERSION,             /* Plugin version */
                  CPL_PLUGIN_TYPE_RECIPE,            /* Plugin type */
                  RECIPE_ID,                         /* Plugin name */
                  xsh_scired_ifu_offset_description_short,   /* Short help */
                  xsh_scired_ifu_offset_description,        /* Detailed help */
                  RECIPE_AUTHOR,                     /* Author name */
                  RECIPE_CONTACT,                    /* Contact address */
                  xsh_get_license(),                 /* Copyright */
                  xsh_scired_ifu_offset_create,
                  xsh_scired_ifu_offset_exec,
                  xsh_scired_ifu_offset_destroy);

  cpl_pluginlist_append(list, plugin);

  return (cpl_error_get_code() != CPL_ERROR_NONE);
}

/*----------------------------------------------------------------------------*/
/**
   @brief    Setup the recipe options
   @param    plugin  the plugin
   @return   0 if everything is ok

   Create the recipe instance and make it available to the application using the
   interface.

*/
/*----------------------------------------------------------------------------*/

static int xsh_scired_ifu_offset_create(cpl_plugin *plugin){
  cpl_recipe *recipe = NULL;
  cpl_parameter* p=NULL;
  char paramname[256];
  char recipename[256];

  xsh_clipping_param crh_clip_param = {5.0, 5, 0.7, 0,0.3};
  /* First param (conv_kernel) should be initialized correctly ! */
  xsh_remove_crh_single_param crh_single = { 0.1, 5, 2.0, 4} ;
  xsh_rectify_param rectify = { "tanh",
                                CPL_KERNEL_DEFAULT, 
                                2,
                                XSH_WAVE_BIN_SIZE_PIPE_NIR, 
                                XSH_SLIT_BIN_SIZE_PIPE_NIR,
                                1,0,0.};
  xsh_stack_param stack_param = {"median",5.,5.};
  /* 2nd and 3rd params should be initialized correctly */
  xsh_localize_obj_param loc_obj = 
        {10, 0.1, 0, 0, LOC_MANUAL_METHOD, 0, 2.0,3,3,FALSE};
  xsh_extract_param extract_par = 
    { LOCALIZATION_METHOD};
  xsh_interpolate_bp_param ipol_par = {30 };
  /* Reset library state */
  xsh_init();

  /* Check input */
  assure( plugin != NULL, CPL_ERROR_NULL_INPUT, "Null plugin");
  /* Get the recipe out of the plugin */
  assure( cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE,
          CPL_ERROR_TYPE_MISMATCH,
          "Plugin is not a recipe");

  recipe = (cpl_recipe *)plugin;

  /* Create the parameter list in the cpl_recipe object */
  recipe->parameters = cpl_parameterlist_new();
  assure( recipe->parameters != NULL,
          CPL_ERROR_ILLEGAL_OUTPUT,
          "Memory allocation failed!");

  /* Set generic parameters (common to all recipes) */
  check( xsh_parameters_generic( RECIPE_ID, recipe->parameters ) ) ;
  xsh_parameters_decode_bp(RECIPE_ID,recipe->parameters,-1);
  check( xsh_parameters_pre_overscan( RECIPE_ID, recipe->parameters ) ) ;
  check(xsh_parameters_stack_create(RECIPE_ID,recipe->parameters,stack_param));
  /* crh clipping params */
  check(xsh_parameters_clipping_crh_create(RECIPE_ID,recipe->parameters,
    crh_clip_param));

  /* subtract_background_params */
  check(xsh_parameters_background_create(RECIPE_ID,recipe->parameters));

  /* remove_crh_single */
  check(xsh_parameters_remove_crh_single_create(RECIPE_ID,recipe->parameters,
						crh_single )) ;
  /* xsh_rectify */
  check(xsh_parameters_rectify_create(RECIPE_ID,recipe->parameters,
					    rectify )) ;
  /* xsh_localize_object */
  check(xsh_parameters_localize_obj_create(RECIPE_ID,recipe->parameters,
					   loc_obj )) ;
  /* trivial extract (Just temporary) */
  check(xsh_parameters_extract_create(RECIPE_ID,
				      recipe->parameters,
				      extract_par,LOCALIZATION_METHOD )) ;

  check(xsh_parameters_interpolate_bp_create(RECIPE_ID,
                recipe->parameters,ipol_par)) ;

  check( xsh_parameters_new_double( recipe->parameters, RECIPE_ID,
    "shift-offsettab-low", 0.0,
     "Global shift of the lower slitlet slit positions, relative to the central one[arcsec]."));
check( xsh_parameters_new_double( recipe->parameters, RECIPE_ID,
    "shift-offsettab-up", 0.0,
     "Global shift of the upper slitlet slit positions, relative to the central one[arcsec]."));

  check( xsh_parameters_new_boolean( recipe->parameters, RECIPE_ID,
    "compute-map", TRUE,
     "if TRUE recompute (wave and slit) maps from the dispersion solution. If sky-subtract is set to TRUE this must be set to TRUE."));
  
  check( xsh_parameters_new_boolean( recipe->parameters, RECIPE_ID,
    "check-afc", TRUE,
     "Input AFC corrected model/wave solution and science frame check."\
     "If TRUE the recipe verify that the input mode/wave solution is AFC corrected,"\
     " its INS.OPTIi.NAME is 'Pin_0.5 ', and its OBS.ID and OBS.TARG.NAME values"\
     " matches with the corresponding values of the science frame."));
     
   sprintf(recipename,"xsh.%s",RECIPE_ID);
  sprintf(paramname,"%s.%s",recipename,"flat-method");
  check( p = cpl_parameter_new_enum( paramname,CPL_TYPE_STRING,
				   "method adopted for flat:",
				   recipename,"master",
                                   2,"master","blaze"));

  check(cpl_parameter_set_alias( p,CPL_PARAMETER_MODE_CLI,
    "flat-method"));
  check(cpl_parameterlist_append( recipe->parameters, p));
  
  cleanup:
    if ( cpl_error_get_code() != CPL_ERROR_NONE ){
      xsh_error_dump(CPL_MSG_ERROR);
      return 1;
    }
    else {
      return 0;
    }
}

/*----------------------------------------------------------------------------*/
/**
   @brief    Execute the plugin instance given by the interface
   @param    plugin  the plugin
   @return   0 if everything is ok
*/
/*----------------------------------------------------------------------------*/

static int xsh_scired_ifu_offset_exec(cpl_plugin *plugin) {
  cpl_recipe *recipe = NULL;

  /* Check parameter */

  assure( plugin != NULL, CPL_ERROR_NULL_INPUT, "Null plugin");

  /* Get the recipe out of the plugin */
  assure( cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE,
          CPL_ERROR_TYPE_MISMATCH, "Plugin is not a recipe");

  recipe = (cpl_recipe *)plugin;

  /* Check recipe */
  xsh_scired_ifu_offset(recipe->parameters, recipe->frames);

  cleanup:
    if ( cpl_error_get_code() != CPL_ERROR_NONE ) {
      xsh_error_dump(CPL_MSG_ERROR);
      xsh_error_reset();
      return 1;
    }
    else {
      return 0;
    }
}


static cpl_error_code 
xsh_params_monitor(xsh_background_param* backg,
                   xsh_rectify_param * rectify_par,
                   xsh_localize_obj_param * loc_obj_par)
{


  xsh_msg_dbg_low("bkg params: sampley=%d radius_y=%d",
	  backg->sampley,backg->radius_y);

  xsh_msg_dbg_low("bkg params: radius_x=%d",
	  backg->radius_x);

  xsh_msg_dbg_low("rectify params: radius=%g bin_lambda=%g bin_space=%g",
	  rectify_par->rectif_radius,rectify_par->rectif_bin_lambda,
	  rectify_par->rectif_bin_space);

  xsh_msg_dbg_low("localize params: chunk_nb=%d nod_step=%g",
	  loc_obj_par->loc_chunk_nb,loc_obj_par->nod_step);

  return cpl_error_get_code();

}
/*--------------------------------------------------------------------------*/
/**
  @brief    scale relevant input parameters for binning
  @param    raws   the frames list
  @param    backg  structure to control inter-order background computation

  In case of failure the cpl_error_code is set.
 */
/*--------------------------------------------------------------------------*/

static cpl_error_code 
xsh_params_bin_scale(cpl_frameset* raws,
                     xsh_background_param* backg)
{

  cpl_frame* frame=NULL;
  const char* name=NULL;
  cpl_propertylist* plist=NULL;
  int binx=0;
  int biny=0;

  check(frame=cpl_frameset_get_frame(raws,0));
  check(name=cpl_frame_get_filename(frame));
  check(plist=cpl_propertylist_load(name,0));
  check(binx=xsh_pfits_get_binx(plist));
  check(biny=xsh_pfits_get_biny(plist));
  xsh_free_propertylist(&plist);

  if(biny>1) {

    /*
    backg->sampley=backg->sampley/biny;
    Not bin dependent.
    */

    backg->radius_y=backg->radius_y/biny;

    /*
    rectify_par->rectif_radius=rectify_par->rectif_radius/biny;
    Rectify Interpolation radius.
    For the moment not bin dependent, but for optimal results probably yes
    */

    /*
    rectify_par->rectif_bin_lambda=rectify_par->rectif_bin_lambda/biny;
    Rectify Wavelength Step.
    For the moment not bin dependent, but for optimal results probably yes
    */

    /*
    loc_obj_par->loc_chunk_nb=loc_obj_par->loc_chunk_nb/biny;
    Localization Nb of chunks.
    Not bin dependent
    */
  }


  if(binx>1) {

    backg->radius_x=backg->radius_x/binx;

    /*
    rectify_par->rectif_bin_space=rectify_par->rectif_bin_space/binx;
    Rectify Position Step.
    For the moment not bin dependent, but for optimal results probably yes
    */

    /*
    loc_obj_par->nod_step=loc_obj_par->nod_step/binx;
    Step (arcsec) between A and B images in nodding mode.
    For the moment not bin dependent, but for optimal results probably yes
    */
  }
 
 cleanup:
  xsh_free_propertylist(&plist);
  return cpl_error_get_code();

}


/*----------------------------------------------------------------------------*/
/**
   @brief    Destroy what has been created by the 'create' function
   @param    plugin  the plugin
   @return   0 if everything is ok
*/
/*----------------------------------------------------------------------------*/
static int xsh_scired_ifu_offset_destroy(cpl_plugin *plugin)
{
  cpl_recipe *recipe = NULL;

  /* reset error state before detroying recipe */
  xsh_error_reset(); 
  /* Check parameter */
  assure( plugin != NULL, CPL_ERROR_NULL_INPUT, "Null plugin" );

  /* Get the recipe out of the plugin */
  assure( cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE,
    CPL_ERROR_TYPE_MISMATCH, "Plugin is not a recipe");

  recipe = (cpl_recipe *)plugin;

  xsh_free_parameterlist(&recipe->parameters);

 cleanup:
  if (cpl_error_get_code() != CPL_ERROR_NONE)
    {
      return 1;
    }
  else
    {
      return 0;
    }
}

/*----------------------------------------------------------------------------*/
/**
   @brief    Interpret the command line options and execute the data processing
   @param    parameters     the parameters list
   @param    frameset   the frames list

   In case of failure the cpl_error_code is set.
*/
/*----------------------------------------------------------------------------*/
static void xsh_scired_ifu_offset( cpl_parameterlist* parameters, 
				   cpl_frameset* frameset)
{
   const char* recipe_tags[4] = {XSH_OBJECT_IFU_OFFSET, XSH_STD_TELL_IFU_OFFSET, XSH_STD_FLUX_IFU_OFFSET, XSH_SKY_IFU};
  int recipe_tags_size = 4;

  /* Input frames */
  cpl_frameset* raws = NULL;
  cpl_frameset* calib = NULL;
  /* Beware, do not "free" the following input frames, they are part
     of the input frameset */
  cpl_frame* bpmap = NULL;
  cpl_frame * master_bias = NULL ;
  cpl_frame * master_dark = NULL ;
  cpl_frame* master_flat = NULL;
  cpl_frame* order_tab_edges = NULL;
  cpl_frameset *wavetab_frameset = NULL ;
  cpl_frameset *shiftifu_frameset = NULL;
  cpl_frameset *nshiftifu_frameset = NULL;
  cpl_frame * model_config_frame = NULL ;
  cpl_frame * wavemap_frame = NULL ;
  cpl_frame * slitmap_frame = NULL;
  cpl_frame * spectral_format = NULL ;
  cpl_frame *disp_tab_frame = NULL;
  cpl_frameset * object_frameset = NULL, * sky_frameset = NULL ;

  /* Parameters */
  xsh_background_param* backg_par = NULL;
  xsh_remove_crh_single_param * crh_single_par = NULL ;
  xsh_rectify_param * rectify_par = NULL ;
  xsh_localize_obj_param * loc_obj_par = NULL ;
  xsh_extract_param * extract_par = NULL ;
  double offset_low =0.0;
  double offset_up =0.0;

  int recipe_use_model = FALSE;
  int do_computemap = 0;
  int check_afc = TRUE;
  
  xsh_instrument* instrument = NULL;
  int nb_sub_frames ;
  int nb_raw_frames ;

  /* Intermediate frames */

  cpl_frameset * sub_frameset = NULL ;	/**< frameset of subtracted offset frames */
  cpl_frameset * rmbkg_frameset = NULL ; /**< frameset of frames after 
					  subtract bkg */
  cpl_frameset * nocrh_frameset = NULL;					  
  cpl_frameset * clean_frameset = NULL ; /**< frameset of clean frames after
					  divide flat */
  cpl_frame * first_frame = NULL;
  cpl_frame * comb_frame = NULL ; /**< Comined frame */
  cpl_frameset * rect2_frameset = NULL ; /**< Rectifid frame set */
  //cpl_frameset * loc_table_frameset = NULL ; /**< Output of xsh_localize_object */

  /* Output Frames (results)*/
  cpl_frameset * res_1D_frameset = NULL ;	/**< Final (result) frame */
  cpl_frameset * res_2D_frameset = NULL ;
  cpl_frame * data_cube = NULL ;
  cpl_frameset * ext_frameset = NULL ;
  cpl_frameset * ext_frameset_tables = NULL ;

  int i ;
  char  file_name[256], arm_str[16] ;
  char file_tag[256];
  cpl_frame* grid_back=NULL;
  cpl_frame* frame_backg=NULL;
  cpl_frameset * ext_frameset_images = NULL ; /**< frameset of rectified frames */
  cpl_frameset * rect2_frameset_tables = NULL ; /**< frameset of rectified frames */
  cpl_frameset * rect2_frameset_tab=NULL;
  cpl_frameset * rect2_frameset_eso=NULL;
  char *rec_prefix = NULL;
  int pre_overscan_corr=0;

  char* flat_method = NULL;
  cpl_frame * blaze_frame = NULL;
  cpl_propertylist* plist=NULL;
  const char* name=NULL;
  const char* tag="";
  int naxis2=0;
  cpl_frame* qc_trace_frame=NULL;
  int save_size=0;
  const int peack_search_hsize=5;
  int method=0;
  
  xsh_stack_param* stack_par=NULL;
  int merge_par=0;
  /**************************************************************************/
  /* DFS management */
  /**************************************************************************/
  check( xsh_begin( frameset, parameters, &instrument, &raws, &calib,
                    recipe_tags, recipe_tags_size,
                    RECIPE_ID, XSH_BINARY_VERSION,
                    xsh_scired_ifu_offset_description_short));

  assure( instrument->mode == XSH_MODE_IFU, CPL_ERROR_ILLEGAL_INPUT,
	  "Instrument NOT in Ifu Mode" ) ;

  xsh_recipe_params_check(parameters,instrument,RECIPE_ID);
  xsh_ensure_raws_input_offset_recipe_is_proper(&raws,instrument);
  /* One should have a multiple of 2 input frames: A-B */
  check( nb_raw_frames = cpl_frameset_get_size( raws ) ) ;
  xsh_msg_dbg_low( "Nb of Raw frames: %d", nb_raw_frames ) ;
  XSH_ASSURE_NOT_ILLEGAL( nb_raw_frames > 1  ) ;
  {
    int even_nb = nb_raw_frames % 2 ;
    XSH_ASSURE_NOT_ILLEGAL( even_nb == 0 ) ;
  }

  check( rec_prefix = xsh_set_recipe_file_prefix( raws,
    RECIPE_ID));


  /**************************************************************************/
  /* Recipe frames */
  /**************************************************************************/

  check(bpmap = xsh_find_master_bpmap(calib));

  /* In UVB and VIS mode */
  if ( xsh_instrument_get_arm(instrument) != XSH_ARM_NIR){
    /* RAWS frameset must have only one file */
    check( master_bias = xsh_find_frame_with_tag(calib,XSH_MASTER_BIAS,
						 instrument));
  }
  /* IN NIR mode */
  else {
    /* split on and off files */
    /*check(xsh_dfs_split_nir(raws,&on,&off));
    XSH_ASSURE_NOT_ILLEGAL(cpl_frameset_get_size(on) >= 3);
    XSH_ASSURE_NOT_ILLEGAL(cpl_frameset_get_size(off) >= 3);*/
  }

  check(order_tab_edges = xsh_find_order_tab_edges(calib,instrument));

  /* one should have either model config frame or wave sol frame */
  if((model_config_frame = xsh_find_frame_with_tag(calib,
                                                   XSH_MOD_CFG_OPT_AFC,
                                               instrument)) == NULL) {

     xsh_error_reset();

     if ((model_config_frame = xsh_find_frame_with_tag(calib,XSH_MOD_CFG_TAB, 
                                               instrument)) == NULL) {
     xsh_error_reset();
     }

  }

  cpl_error_reset() ;

  /* OPTIONAL */
  shiftifu_frameset = xsh_find_offset_tab_ifu( calib, 
    instrument);
  xsh_error_reset();
  
  wavetab_frameset = xsh_find_wave_tab_ifu( calib, instrument);
  cpl_error_reset() ;

  /*
    One of model config and wave tab must be present, but only one !
  */
  if ( model_config_frame == NULL){
    xsh_msg("RECIPE USE WAVE SOLUTION");
    recipe_use_model = FALSE;
  }
  else{
    xsh_msg("RECIPE USE MODEL");
    recipe_use_model = TRUE;
  }
  
  XSH_ASSURE_NOT_ILLEGAL( (model_config_frame != NULL && wavetab_frameset == NULL ) ||
			  (model_config_frame == NULL && wavetab_frameset != NULL ) );

  check( master_flat = xsh_find_master_flat( calib, instrument ) ) ;

  if((master_dark = xsh_find_frame_with_tag(calib,XSH_MASTER_DARK,
					    instrument)) == NULL){
    xsh_msg_warning("Frame %s not provided",XSH_MASTER_DARK);
    xsh_error_reset();
  }

  check( spectral_format = xsh_find_spectral_format( calib, instrument ) ) ;


  /**************************************************************************/
  /* Recipe parameters */
  /**************************************************************************/
  check( stack_par = xsh_stack_frames_get( RECIPE_ID, parameters));

  check( backg_par = xsh_parameters_background_get(RECIPE_ID,
    parameters));

  check( loc_obj_par = xsh_parameters_localize_obj_get(RECIPE_ID,
     parameters));
  check( rectify_par = xsh_parameters_rectify_get(RECIPE_ID,
     parameters));
  rectify_par->conserve_flux=FALSE;
  check( crh_single_par = xsh_parameters_remove_crh_single_get(RECIPE_ID,
    parameters));

  check(extract_par=xsh_parameters_extract_get(RECIPE_ID, parameters));

  check( do_computemap = xsh_parameters_get_boolean( parameters, RECIPE_ID,
    "compute-map"));

  check( check_afc = xsh_parameters_get_boolean( parameters, RECIPE_ID,
    "check-afc"));

  if ( do_computemap && recipe_use_model==FALSE){
    check( disp_tab_frame = xsh_find_disp_tab( calib, instrument));
  }
  
  check(xsh_rectify_params_set_defaults(parameters,RECIPE_ID,instrument,rectify_par));

  /* adjust relevant parameter to binning */
  if ( xsh_instrument_get_arm( instrument ) != XSH_ARM_NIR ) {
    check(xsh_params_bin_scale(raws,backg_par));
  }
  check(xsh_params_monitor(backg_par,rectify_par,loc_obj_par));
  
  check( offset_low = xsh_parameters_get_double( parameters, RECIPE_ID,
    "shift-offsettab-low"));

  check( offset_up = xsh_parameters_get_double( parameters, RECIPE_ID,
    "shift-offsettab-up"));

  /* update slitlets with manual shift */
  if ( shiftifu_frameset != NULL){
    xsh_msg("offset low %f up %f", offset_low, offset_up);
    check( nshiftifu_frameset = xsh_shift_offsettab( shiftifu_frameset,
      offset_low, offset_up));
  }

  /**************************************************************************/
  /* Recipe code */
  /**************************************************************************/

  /* prepare RAW frames in PRE format */
  check(xsh_prepare(raws, bpmap, master_bias, XSH_OBJECT_IFU_OFFSET,
		    instrument,pre_overscan_corr,CPL_TRUE));
  check( first_frame = cpl_frameset_get_frame( raws, 0));
		    
  /* Get wavemap and slitmap */
  check( xsh_check_get_map( disp_tab_frame, order_tab_edges,
    first_frame, model_config_frame, calib, instrument,
    do_computemap, recipe_use_model, rec_prefix,
    &wavemap_frame, &slitmap_frame));

  /* Separate OBJECT and SKY frames */
  check( nb_sub_frames = xsh_dfs_split_offset( raws, XSH_OBJECT_IFU_OFFSET,
					   XSH_SKY_IFU, &object_frameset,
					   &sky_frameset ));

  /**************************************************************************/
  /* Check that OBJECT IFU frame and AFC corrected CFG are proper              */
  /**************************************************************************/
  for( i = 0 ; i<nb_sub_frames ; i++ ) {
    cpl_frame *frame = NULL;
    
    frame = cpl_frameset_get_frame( object_frameset, i );
    check( xsh_check_afc( check_afc, model_config_frame, 
      frame, wavetab_frameset, order_tab_edges, disp_tab_frame, 
      instrument));
  }
  /**************************************************************************/
  /* Check that SKY IFU frame and AFC corrected CFG are proper              */
  /**************************************************************************/
  for( i = 0 ; i<nb_sub_frames ; i++ ) {
    cpl_frame *frame = NULL;
    
    frame = cpl_frameset_get_frame( sky_frameset, i );
    check( xsh_check_afc( check_afc, model_config_frame, 
      frame, wavetab_frameset, order_tab_edges, disp_tab_frame, 
      instrument));
  }  
  
					   
  /* For each pair, subtract OBJECT-SKY */
  check( sub_frameset = xsh_subtract_sky_offset( object_frameset, sky_frameset,
						 nb_sub_frames, instrument )) ;
  check( rmbkg_frameset = cpl_frameset_new() ) ;
  check( nocrh_frameset = cpl_frameset_new() ) ;
  check( clean_frameset = cpl_frameset_new() ) ;

  sprintf( arm_str, "%s_",  xsh_instrument_arm_tostring(instrument) ) ;


  /* For each sky subtracted frame */
  for( i = 0 ; i<nb_sub_frames ; i++ ) {
    cpl_frame * a_b = NULL ;
    cpl_frame * rm_bkg = NULL ;
    char str[16] ;

    sprintf( str, "%d", i ) ;
    a_b = cpl_frameset_get_frame( sub_frameset, i ) ;
 
    /* subtract background */
    xsh_msg("Subtract inter-order background %d", i );
    sprintf(file_name, "%s%s",rec_prefix, str) ;
    xsh_free_frame( &frame_backg);
    check(rm_bkg = xsh_subtract_background( a_b,
					    order_tab_edges,
					    backg_par, instrument,
					    file_name,&grid_back,
					    &frame_backg,0,0,0));
 
    check( cpl_frameset_insert( rmbkg_frameset, rm_bkg ) ) ;
  }
  

  check( flat_method = xsh_parameters_get_string( parameters, RECIPE_ID,
    "flat-method"));    
  if ( strcmp( flat_method, "master") != 0){
    xsh_msg("---Create blaze image");
    check( blaze_frame = xsh_blaze_image( master_flat, order_tab_edges,
     instrument));
  }
  
  if ( nb_sub_frames < 3 && crh_single_par->nb_iter > 0 ) {
    xsh_msg( "Less than 3 frames AND crh_single_niter > 0" ) ;
    for ( i = 0 ; i < nb_sub_frames ; i++ ) {
      cpl_frame * divided = NULL ;
      cpl_frame * rm_crh = NULL ;
      cpl_frame * a_b = NULL ;

      check( a_b = cpl_frameset_get_frame( rmbkg_frameset, i ) ) ;
      sprintf( file_tag, "NO_CRH_IFU_OFFSET_%s%d", arm_str,i);
      xsh_msg( "Remove crh (single frame)" );
      check( rm_crh = xsh_remove_crh_single( a_b,instrument,NULL,
					     crh_single_par,
					     file_tag ));
      check( cpl_frameset_insert( nocrh_frameset, rm_crh));
      
      xsh_msg( "Divide by flat" ) ;
      sprintf( file_tag, "FF_IFU_OFFSET_%s%d", arm_str, i);
      if ( strcmp( flat_method, "master") == 0){
        check( divided = xsh_divide_flat( rm_crh, master_flat, 
          file_tag, instrument));
      }
      else{
        check( divided = xsh_divide_by_blaze( rm_crh, 
          blaze_frame, instrument));
      }
      
      check( cpl_frameset_insert( clean_frameset, divided));
    }
  }
  else for( i = 0 ; i < nb_sub_frames ; i++ ) {
    cpl_frame * divided = NULL ;
    cpl_frame * a_b = NULL ;

    /* If enough frames, the CRH removal is done in xsh_combine_offset */
    a_b = cpl_frameset_get_frame( rmbkg_frameset, i ) ;

    /* Divide by flat */
    xsh_msg( "Divide by flat" ) ;
    sprintf( file_tag, "FF_IFU_OFFSET_%s%d", arm_str, i);
    
    if ( strcmp( flat_method, "master") == 0){
      check( divided = xsh_divide_flat( a_b, master_flat, 
        file_tag, instrument));
    }
    else{
      check( divided = xsh_divide_by_blaze( a_b, 
        blaze_frame, instrument));
    }
    check( cpl_frameset_insert( clean_frameset, divided ) ) ;
  }


  /* Now combine all frames */
  xsh_msg( "Combining all frames" );
  sprintf( file_tag, "COMBINED_IFU_OFFSET_%s_ALL", arm_str);


  check( comb_frame = xsh_combine_offset( clean_frameset,
					  file_tag, stack_par,
					  instrument, NULL, NULL,0));


  /* Now rectify the combined frame */
  xsh_msg( "Rectify combined frame" ) ;
  rect2_frameset_eso=cpl_frameset_new();
  rect2_frameset_tab=cpl_frameset_new();
  check( rect2_frameset = xsh_rectify_ifu( comb_frame, order_tab_edges,
					   wavetab_frameset,
					   nshiftifu_frameset,
					   model_config_frame,
					   instrument, rectify_par,
					   spectral_format,
					   slitmap_frame, &rect2_frameset_eso, 
					   &rect2_frameset_tab,rec_prefix));
					
#if 0
  /* Must localize (if extract-method=localization) */
  if ( extract_par->method == LOCALIZATION_METHOD &&
       loc_table_frameset == NULL ) {
    xsh_msg( "Localize obj ifu frame" ) ;
    check( loc_table_frameset = xsh_localize_obj_ifu( rect2_frameset, NULL,
						      instrument,
						      loc_obj_par, NULL) ) ;
  }

  xsh_msg( "Extract ifu frame" ) ;
  check(rect2_frameset_tables=xsh_frameset_ext_table_frames(rect2_frameset));
  check(ext_frameset = xsh_extract_ifu(rect2_frameset_tables,
                                       loc_table_frameset,
				       instrument, extract_par,rec_prefix )) ;
  xsh_msg( "Merge orders with 1D frame" ) ;
  check(ext_frameset_tables=xsh_frameset_ext_table_frames(ext_frameset));

  check( res_1D_frameset = xsh_merge_ord_ifu( ext_frameset_tables, instrument,
					      merge_par,rec_prefix ));
  xsh_free_frameset(&ext_frameset_tables);
#endif

  

  xsh_msg( "Merge orders with 2D frame" ) ;
  check( res_2D_frameset = xsh_merge_ord_ifu( rect2_frameset,instrument,
					      merge_par,rec_prefix ));
					      
  check( data_cube = xsh_cube( res_2D_frameset, instrument, rec_prefix));

  xsh_msg( "Saving Products for IFU" ) ;
  check( xsh_add_product_pre_3d( data_cube, frameset, parameters,
    RECIPE_ID, instrument));

  name=cpl_frame_get_filename(data_cube);
  plist=cpl_propertylist_load(name,0);
  naxis2=xsh_pfits_get_naxis2(plist);
  xsh_free_propertylist(&plist);
  check( qc_trace_frame=xsh_cube_qc_trace_window(data_cube,
                                                   instrument,tag,rec_prefix,
                                                   save_size+1,
                                                   naxis2-save_size,
                                                   peack_search_hsize,
                                                   method,0));
  if(qc_trace_frame) {
    check( xsh_add_product_table( qc_trace_frame, frameset,parameters, 
					RECIPE_ID, instrument,NULL));
  }
#if 0
  check(ext_frameset_tables=xsh_frameset_ext_table_frames(ext_frameset));
  check(ext_frameset_images=xsh_frameset_ext_image_frames(ext_frameset));
  /* saving products*/ 
  xsh_msg( "Saving Products for IFU" ) ;

  for( i = 0 ; i<3 ; i++ ) {
    cpl_frame * rec_frame = NULL ;
    cpl_frame * ext_frame = NULL ;
    cpl_frame * res1d_frame = NULL ;
    cpl_frame * res2d_frame = NULL ;

    check( rec_frame = cpl_frameset_get_frame( rect_frameset_eso, i ) ) ;
    xsh_msg( "Product from '%s' [%s]",
	     cpl_frame_get_filename( rec_frame ),
	     cpl_frame_get_tag( rec_frame ) ) ;
    check( xsh_add_product_image( rec_frame, frameset, parameters,
				  RECIPE_ID, instrument,NULL));

    check( ext_frame = cpl_frameset_get_frame( ext_frameset_images, i ) ) ;
    xsh_msg( "Product from '%s' [%s]",
	     cpl_frame_get_filename( ext_frame ),
	     cpl_frame_get_tag( ext_frame ) ) ;
    check( xsh_add_product_image( ext_frame, frameset, parameters,
				  RECIPE_ID, instrument,NULL));

    check( res2d_frame = cpl_frameset_get_frame( res_2D_frameset, i ) ) ;
    xsh_msg( "Product from '%s' [%s]",
	     cpl_frame_get_filename( res2d_frame ),
	     cpl_frame_get_tag( res2d_frame ) ) ;
    check( xsh_add_product_pre( res2d_frame, frameset, parameters,
				RECIPE_ID, instrument));


    check( res1d_frame = cpl_frameset_get_frame( res_1D_frameset, i ) ) ;
    check(xsh_monitor_spectrum1D_flux(res1d_frame,instrument));


    xsh_msg( "Product from '%s' [%s]",
	     cpl_frame_get_filename( res1d_frame ),
	     cpl_frame_get_tag( res1d_frame ) ) ;
    check( xsh_add_product_spectrum( res1d_frame, frameset, parameters,
				RECIPE_ID, instrument));

  }
  xsh_free_frameset(&rect2_frameset_tables);
  xsh_free_frameset(&ext_frameset_tables);

  xsh_msg( "Product from '%s' [%s]",
	   cpl_frame_get_filename( data_cube ),
	   cpl_frame_get_tag( data_cube ) ) ;
  check( xsh_add_product_pre_3d( data_cube, frameset, parameters,
				 RECIPE_ID, instrument));

#endif
  cleanup:
    xsh_end( RECIPE_ID, frameset, parameters );
    XSH_FREE( rec_prefix);
    XSH_FREE( backg_par);
    XSH_FREE( crh_single_par);
    XSH_FREE( rectify_par);
    XSH_FREE( loc_obj_par);
    XSH_FREE( stack_par);

    XSH_FREE( extract_par);
    xsh_instrument_free(&instrument);
	
    xsh_free_frameset(&ext_frameset_images);
    xsh_free_frameset(&ext_frameset_tables);

    xsh_free_frameset(&raws);
    xsh_free_frameset(&calib);
    xsh_free_frameset( &wavetab_frameset);
    xsh_free_frameset( &shiftifu_frameset);
    xsh_free_frameset( &nshiftifu_frameset);
    xsh_free_frameset( &object_frameset);
    xsh_free_frameset( &sky_frameset);
    xsh_free_frameset( &sub_frameset ) ;
    xsh_free_frameset( &nocrh_frameset);
    xsh_free_frameset( &clean_frameset ) ;
    xsh_free_frameset( &rmbkg_frameset ) ;
    xsh_free_frameset(&res_1D_frameset) ;
    xsh_free_frameset(&res_2D_frameset) ;
    
    xsh_free_frameset( &rect2_frameset) ;
    xsh_free_frameset( &rect2_frameset_eso);
    xsh_free_frameset( &rect2_frameset_tab);
    xsh_free_frameset(&rect2_frameset_tables);
    
    xsh_free_frameset(&ext_frameset) ;
    xsh_free_frame( &slitmap_frame);
    xsh_free_frame( &wavemap_frame);
    xsh_free_frame( &comb_frame);
    xsh_free_frame( &data_cube);
    xsh_free_frame( &grid_back);
    xsh_free_frame( &frame_backg);
    xsh_free_frame( &blaze_frame);
    xsh_free_frame( &qc_trace_frame);
    return;
}

/**@}*/
