/*                                                                            *
 *   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-02-04 12:44:48 $
 * $Revision: 1.63 $
 *
*/

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

/*----------------------------------------------------------------------------*/
/**
 * @defgroup xsh_geom_ifu   xsh_geom_ifu
 * @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>
/* DRL functions */
#include <xsh_drl.h>
#include <xsh_drl_check.h>
#include <xsh_utils_table.h>
#include <xsh_model_utils.h>
#include <xsh_utils_image.h>
#include <xsh_utils_ifu.h>
#include <xsh_blaze.h>
#include <xsh_parameters.h>
#include <xsh_model_arm_constants.h>
/* Library */
#include <cpl.h>
/* CRH Remove */

/*-----------------------------------------------------------------------------
  Defines
  ----------------------------------------------------------------------------*/

#define RECIPE_ID "xsh_geom_ifu"
#define RECIPE_AUTHOR "P.Goldoni, L.Guglielmi, R. Haigron, F. Royer"
#define RECIPE_CONTACT "regis.haigron@obspm.fr"

#define XSH_GEOM_SLIT_BIN_SIZE_PIPE_UVB 0.16
#define XSH_GEOM_SLIT_BIN_SIZE_PIPE_VIS 0.16
#define XSH_GEOM_SLIT_BIN_SIZE_PIPE_NIR 0.2
#define XSH_GEOM_WAVE_BIN_SIZE_PIPE_UVB 0.04
#define XSH_GEOM_WAVE_BIN_SIZE_PIPE_VIS 0.04
#define XSH_GEOM_WAVE_BIN_SIZE_PIPE_NIR 0.1
/*-----------------------------------------------------------------------------
  Functions prototypes
  ----------------------------------------------------------------------------*/

/*
 *   Plugin initalization, execute and cleanup handlers
 */
static cpl_error_code 
xsh_rectify_params_set_defaults_drl(cpl_parameterlist* pars,
                                const char* rec_id,
                                xsh_instrument* inst,
                                xsh_rectify_param * rectify_par);
				
static int xsh_geom_ifu_create(cpl_plugin *);
static int xsh_geom_ifu_exec(cpl_plugin *);
static int xsh_geom_ifu_destroy(cpl_plugin *);

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

/*-----------------------------------------------------------------------------
  Static variables
  ----------------------------------------------------------------------------*/
static char xsh_geom_ifu_description_short[] =
"Produces the spatial geometry of the IFU pattern on the sky";

static char xsh_geom_ifu_description[] =
"This recipe Produces the spatial geometry of the IFU pattern on the sky\n\
Input Frames : \n\
  - A set of n science frames ( n == 1 or >=3, Tag = TRACE_arm)\n\
  - [UVB,VIS] A master bias frame (Tag = MASTER_BIAS_arm)\n\
  - [OPTIONAL] A master dark frame (Tag = MASTER_DARK_arm)\n\
  - A master flat frame (Tag = MASTER_FLAT_IFU_arm)\n\
  - An AFC corrected model order edges table for IFU frame (Tag = ORDER_TAB_AFC_IFU_arm)\n\
  - [PHYSMOD] An AFC corrected model cfg frame (Tag = XSH_MOD_CFG_OPT_AFC_arm)\n\
  - [POLY] An AFC corrected model wavesol frame (Tag = WAVE_TAB_AFC_arm)\n\
  -  An AFC corrected dispersion solution frame (Tag = DISP_TAB_AFC_arm)\n\
  - [OPTIONAL] A badpixel map (Tag = BADPIXEL_MAP_arm)\n\
Products : \n\
  - A set of shift offset tables (Tag = OFFSET_TAB_slitlet_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_geom_ifu_description_short, /* Short help */
                  xsh_geom_ifu_description,       /* Detailed help */
                  RECIPE_AUTHOR,                     /* Author name */
                  RECIPE_CONTACT,                    /* Contact address */
                  xsh_get_license(),                 /* Copyright */
                  xsh_geom_ifu_create,
                  xsh_geom_ifu_exec,
                  xsh_geom_ifu_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_geom_ifu_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, 4, 
                                -1, 
                                -1,
				1, 0, 0};
  xsh_localize_ifu_param loc_ifu =
    { 3, 5, 2, 0.05, 0.95, 0.05, 0.95, 0.0, 0.0, 0, FALSE, 50};

  xsh_stack_param stack_param = {"median",5.,5.};

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

  /* localize_ifu */
   check(xsh_parameters_localize_ifu_create(RECIPE_ID,recipe->parameters,
                                           loc_ifu)) ;
  /* correct ifu */
  check( xsh_parameters_new_int( recipe->parameters, RECIPE_ID,
    "correctifu-niter", 3,
    "Number of iterations in computing the localization shifts of the IFU slitlets"));
  check( xsh_parameters_new_double( recipe->parameters, RECIPE_ID,
    "correctifu-lambdaref", -1,
    "Reference wavelength where the reference localization on the slit is chosen"));
  check( xsh_parameters_new_double( recipe->parameters, RECIPE_ID,
    "correctifu-lambdaref-hsize", 2.5,
    "HAlf size in nm to estimate reference wavelength"));  
    
  check( xsh_parameters_new_boolean( recipe->parameters, RECIPE_ID,
    "do-cube", FALSE,
    "if TRUE creates a data cube"));

  check( xsh_parameters_new_boolean( recipe->parameters, RECIPE_ID,
    "compute-map", TRUE,
     "if TRUE recompute (wave and slit) maps from the dispersion solution."));
     
  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,"blaze",
                                   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    Scales input parameters for binning 
  @param    raws   the frames list
  @param    backg  the structure controlling 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
    */

  }
 
 cleanup:
  xsh_free_propertylist(&plist);
  return cpl_error_get_code();

}

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

static int xsh_geom_ifu_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_geom_ifu(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;
  }
}

/*----------------------------------------------------------------------------*/
/**
   @brief    Destroy what has been created by the 'create' function
   @param    plugin  the plugin
   @return   0 if everything is ok
*/
/*----------------------------------------------------------------------------*/
static int xsh_geom_ifu_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;
    }
}

static cpl_error_code 
xsh_params_monitor(xsh_background_param* backg,
                   xsh_rectify_param * rectify_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);

  return cpl_error_get_code();

}

static cpl_error_code 
xsh_params_set_defaults(cpl_parameterlist* pars,
                        xsh_instrument* inst,
                        xsh_rectify_param * rectify_par, 
                        double* lambda_ref)
{
   cpl_parameter *p=NULL;
 
   check(p=xsh_parameters_find(pars,RECIPE_ID,"correctifu-lambdaref"));
   if(cpl_parameter_get_double(p) <= 0) {
      if (xsh_instrument_get_arm(inst) == XSH_ARM_NIR){
         *lambda_ref= XSH_CORRECTIFU_LAMBDAREF_PIPE_NIR;
      }
      else {
         if (xsh_instrument_get_arm(inst) == XSH_ARM_UVB){
            *lambda_ref= XSH_CORRECTIFU_LAMBDAREF_PIPE_UVB;
         }
         else{
            *lambda_ref= XSH_CORRECTIFU_LAMBDAREF_PIPE_VIS;
         }
      }
      cpl_parameter_set_double(p, *lambda_ref);
   }

   check(xsh_rectify_params_set_defaults_drl(pars,RECIPE_ID,inst,rectify_par));
 
  cleanup:
    return cpl_error_get_code();

}


static cpl_error_code 
xsh_rectify_params_set_defaults_drl(cpl_parameterlist* pars,
                                const char* rec_id,
                                xsh_instrument* inst,
                                xsh_rectify_param * rectify_par)
{
   cpl_parameter* p=NULL;
 
   check(p=xsh_parameters_find(pars,rec_id,"rectify-bin-slit"));
   if(cpl_parameter_get_double(p) <= 0) {
      if (xsh_instrument_get_arm(inst) == XSH_ARM_UVB){
        rectify_par->rectif_bin_space=XSH_GEOM_SLIT_BIN_SIZE_PIPE_UVB;
        cpl_parameter_set_double(p,XSH_GEOM_SLIT_BIN_SIZE_PIPE_UVB);
      } else if (xsh_instrument_get_arm(inst) == XSH_ARM_VIS){
        rectify_par->rectif_bin_space=XSH_GEOM_SLIT_BIN_SIZE_PIPE_VIS;
        cpl_parameter_set_double(p,XSH_GEOM_SLIT_BIN_SIZE_PIPE_VIS);
      } else if (xsh_instrument_get_arm(inst) == XSH_ARM_NIR){
        rectify_par->rectif_bin_space=XSH_GEOM_SLIT_BIN_SIZE_PIPE_NIR;
        cpl_parameter_set_double(p,XSH_GEOM_SLIT_BIN_SIZE_PIPE_NIR);
      }
   }
   check(p=xsh_parameters_find(pars,rec_id,"rectify-bin-lambda"));
   if(cpl_parameter_get_double(p) <= 0) {
      if (xsh_instrument_get_arm(inst) == XSH_ARM_UVB){
        rectify_par->rectif_bin_lambda=XSH_GEOM_WAVE_BIN_SIZE_PIPE_UVB;
        cpl_parameter_set_double(p,XSH_GEOM_WAVE_BIN_SIZE_PIPE_UVB);
      } else if (xsh_instrument_get_arm(inst) == XSH_ARM_VIS){
        rectify_par->rectif_bin_lambda=XSH_GEOM_WAVE_BIN_SIZE_PIPE_VIS;
        cpl_parameter_set_double(p,XSH_GEOM_WAVE_BIN_SIZE_PIPE_VIS);
      } else if (xsh_instrument_get_arm(inst) == XSH_ARM_NIR){
        rectify_par->rectif_bin_lambda=XSH_GEOM_WAVE_BIN_SIZE_PIPE_NIR;
        cpl_parameter_set_double(p,XSH_GEOM_WAVE_BIN_SIZE_PIPE_NIR);
      }
   }

 cleanup:
 
  return cpl_error_get_code();

}

/*----------------------------------------------------------------------------*/
/**
   @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_geom_ifu(cpl_parameterlist* parameters,
				  cpl_frameset* frameset)
{
  const char* recipe_tags[1] = {XSH_TRACE};
  int recipe_tags_size = 1;

  /* 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 *masterflat_frame = NULL;
  cpl_frame *order_tab_edges = NULL;
  cpl_frameset *wave_tabs_ifu = NULL ;
  cpl_frame *model_config_frame = NULL ;
  cpl_frame *wavemap_frame = NULL ;
  cpl_frame *spectralformat_frame = NULL ;
  cpl_frame *slitmap_frame = NULL ;
  cpl_frame *disp_tab_frame = NULL;
  cpl_frame *skymask_frame = NULL;

  /* Parameters */
  xsh_clipping_param *crh_clipping_par = NULL;
  xsh_background_param *backg_par = NULL;
  xsh_remove_crh_single_param *crh_single_par = NULL ;
  xsh_rectify_param *rectify_par = NULL ;
  int merge_par = 0;
  xsh_localize_ifu_param *loc_ifu_par = NULL ;
  xsh_stack_param* stack_par=NULL;
  char* flat_method = NULL;
  int do_computemap = 0,  do_cube=0;
  int check_afc = TRUE;
  int recipe_use_model = FALSE;
  xsh_instrument* instrument = NULL;
  int nb_raw_frames;

  /* Intermediate frames */
#if 0
  cpl_frameset * on = NULL, * off = NULL ; /**< ON and Off frames (NIR only) */
#endif
  cpl_frame * crhm_frame = NULL ;	/**< Output of remove_crh */
  cpl_frame * rmbias = NULL;	/**< Output of subtract bias */
  cpl_frame * rmdark = NULL;	/**< Output of subtract dark */
  cpl_frame * rmbkg = NULL ;	/**< Output of subtract background */
  cpl_frame * blaze_frame = NULL;
  cpl_frame *div_frame = NULL ; /**< Output of xsh_divide_flat */
  cpl_frameset *rect_frameset = NULL ; /**< Output of xsh_rectify_ifu */
  cpl_frame * clean_frame = NULL ; /**< Output of remove_crh_single */

  /* Output Frames (results)*/
  cpl_frame* grid_backg=NULL;
  cpl_frame* frame_backg=NULL;
  cpl_frameset* rect_frameset_eso=NULL;
  cpl_frameset* rect_frameset_tab=NULL;
  cpl_frameset *shiftifu_frameset=NULL;
  cpl_frameset *shiftifu_old_frameset = NULL;
  cpl_frameset *merge_frameset=NULL;
  cpl_frameset *locifu_frameset=NULL;
  cpl_frame *data_cube = NULL ;
  
  const char* ftag=NULL;
  char tag[256];
  char *rec_prefix = NULL;
  char geom_prefix[256];
  
  int pre_overscan_corr=0;
  int i, geom_niter = 1;
  double lambda_ref;
  double lambdaref_hsize;
  
  /**************************************************************************/
  /* DFS management */
  /**************************************************************************/
  check( xsh_begin( frameset, parameters, &instrument, &raws, &calib,
    recipe_tags, recipe_tags_size,RECIPE_ID, XSH_BINARY_VERSION,
    xsh_geom_ifu_description_short));

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

  check(xsh_recipe_params_check(parameters,instrument,RECIPE_ID));

  /* One should have 1 or >=3 input frames. 2 is not permitted */
  check( nb_raw_frames = cpl_frameset_get_size( raws));
  XSH_ASSURE_NOT_ILLEGAL( nb_raw_frames == 1 || nb_raw_frames >= 3 ) ;

  check( rec_prefix = xsh_set_recipe_file_prefix(raws,"xsh_geom_ifu"));

  /**************************************************************************/
  /* Recipe frames */
  /**************************************************************************/
  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_master_bias(calib,instrument));
  }
#if 0
  // Dont care ON/OFF in case of NIR (may change later)
  /* IN NIR mode */
  else {
    /* split on and off files */
    xsh_msg( "Calling xsh_dfs_split_nir" ) ;
    check(xsh_dfs_split_nir(raws, &on, &off));
    xsh_msg( "   Nb ON: %d, OFF: %d", cpl_frameset_get_size(on),
	     cpl_frameset_get_size(off) ) ;
    XSH_ASSURE_NOT_ILLEGAL(cpl_frameset_get_size(on) >= 3);
    XSH_ASSURE_NOT_ILLEGAL(cpl_frameset_get_size(off) >= 3);
  }
#endif

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

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

    wave_tabs_ifu = xsh_find_wave_tab_ifu( calib, instrument);

  }
  //xsh_error_reset();

  if( (model_config_frame!=NULL) && (wave_tabs_ifu != NULL) ) {
    
     xsh_msg_error("You cannot provide both a %s and a %s frame. Decide if you are in poly or physical model mode. We exit",
                   XSH_WAVE_TAB_2D , XSH_MOD_CFG_TAB);
     goto cleanup;                            
  }   
      
  if((model_config_frame==NULL) && ( wave_tabs_ifu == NULL) ) {
     xsh_msg_error("You must provide either a %s or a %s frame",
                   XSH_WAVE_TAB_2D, XSH_MOD_CFG_TAB);
     goto cleanup;
  }

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

  check( masterflat_frame = xsh_find_master_flat( calib, instrument));
  check(spectralformat_frame = xsh_find_spectral_format( calib, instrument ) ) ;

  /**************************************************************************/
  /* Recipe parameters */
  /**************************************************************************/

  recipe_use_model = ( model_config_frame != NULL);
  check( stack_par = xsh_stack_frames_get( RECIPE_ID, parameters));
  check( crh_clipping_par = xsh_parameters_clipping_crh_get(RECIPE_ID,
    parameters));
  check( backg_par = xsh_parameters_background_get(RECIPE_ID,
    parameters));
  check( crh_single_par = xsh_parameters_remove_crh_single_get(RECIPE_ID,
    parameters));

  check( rectify_par = xsh_parameters_rectify_get(RECIPE_ID,
     parameters));

  check( loc_ifu_par = xsh_parameters_localize_ifu_get(RECIPE_ID,
     parameters));
  check( geom_niter = xsh_parameters_get_int( parameters, RECIPE_ID,
    "correctifu-niter"));
  check( lambda_ref = xsh_parameters_get_double( parameters, RECIPE_ID,
    "correctifu-lambdaref"));
  check( lambdaref_hsize = xsh_parameters_get_double( parameters, RECIPE_ID,
    "correctifu-lambdaref-hsize"));
  check( do_cube = xsh_parameters_get_boolean( parameters, RECIPE_ID,
    "do-cube"));
    
  check( do_computemap = xsh_parameters_get_boolean( parameters, RECIPE_ID,
    "compute-map"));

  check( check_afc = xsh_parameters_get_boolean( parameters, RECIPE_ID,
    "check-afc"));
  rectify_par->conserve_flux=FALSE;
  if ( do_computemap && recipe_use_model==FALSE){
    check( disp_tab_frame =  xsh_find_frame_with_tag( calib,XSH_DISP_TAB_AFC, 
						      instrument));
  }
 
  check(xsh_params_set_defaults(parameters,instrument,rectify_par, &lambda_ref));
  /* 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));


  if ( loc_ifu_par->use_skymask == TRUE){
    xsh_msg("Using sky mask");
    check( skymask_frame = xsh_find_frame_with_tag( calib, XSH_SKY_LINE_LIST,
      instrument));
  }

  /**************************************************************************/
  /* Recipe code */
  /**************************************************************************/
  /* prepare RAW frames in XSH format */

  xsh_msg( "---Prepare raws frames");
  check( xsh_prepare( raws, bpmap, master_bias, XSH_OBJECT_IFU_STARE,
		      instrument,pre_overscan_corr,CPL_TRUE));

  /* Removing Cosmic Rays (if more than 2 frames)
   Output frame in PRE format */
  if ( nb_raw_frames >= 3 ) {
    xsh_msg( "---Remove cosmics");

    ftag=XSH_GET_TAG_FROM_ARM(XSH_SLIT_STARE_REMOVE_CRH,instrument);
    check_msg( crhm_frame = xsh_check_remove_crh_multiple( raws,
						   ftag,stack_par,
						   NULL,
						     instrument, NULL,NULL ),
	       "Error in xsh_remove_crh" ) ;
  }
  else {
    /* Only one frame in raws frameset, get it (it's first of course !) */
    check( crhm_frame = cpl_frame_duplicate(cpl_frameset_get_frame( raws,0 )));
  }
  xsh_msg( "created %s", cpl_frame_get_filename( crhm_frame));

  if ( do_computemap){
    if (recipe_use_model){
      char wave_map_tag[256];
      char slit_map_tag[256];
      int found_temp=true;

      check(xsh_model_temperature_update_frame(&model_config_frame,crhm_frame,
                                           instrument,&found_temp));
      
      sprintf(wave_map_tag,"%s_%s",rec_prefix,XSH_WAVE_MAP_MODEL);
      sprintf(slit_map_tag,"%s_%s",rec_prefix,XSH_SLIT_MAP_MODEL);
      check( xsh_create_model_map( model_config_frame, instrument,
                                   wave_map_tag,slit_map_tag, 
                                   &wavemap_frame, &slitmap_frame,1));
    }
    else{
      xsh_msg( "Compute the wave map and the slit map");
      check( xsh_create_map( disp_tab_frame, order_tab_edges,
			     crhm_frame, instrument, 
			     &wavemap_frame, &slitmap_frame,rec_prefix));
    }
    cpl_frameset_insert( calib, wavemap_frame);
    cpl_frameset_insert( calib, slitmap_frame);
  }
  else{
    check( wavemap_frame = xsh_find_wavemap( calib, instrument));
    slitmap_frame = xsh_find_slitmap(calib, instrument);
  }

  check( rmbias = xsh_check_subtract_bias( crhm_frame, master_bias,
                                           instrument, rec_prefix, pre_overscan_corr,0));

  /**************************************************************************/
  /* Check that SCI IFU frame and AFC corrected CFG are proper              */
  /**************************************************************************/
  check( xsh_check_afc( check_afc, model_config_frame, 
    rmbias, wave_tabs_ifu, order_tab_edges, disp_tab_frame, 
    instrument));

  /* Subtract Dark if necessary */
  check( rmdark = xsh_check_subtract_dark( rmbias, master_dark,
    instrument, rec_prefix));

  /* subtract background */
  xsh_msg("---Subtract_background");
  check( rmbkg = xsh_subtract_background( rmdark,
    order_tab_edges, backg_par, instrument, "GEOM_IFU",&grid_backg,
					  &frame_backg,0,0,0 ));

  /* divide by */
  xsh_msg("---Do flatfielding");
  sprintf( tag, "GEOM_IFU_FF_%s", 
    xsh_instrument_arm_tostring(instrument));
  
  check( flat_method = xsh_parameters_get_string( parameters, RECIPE_ID,
    "flat-method"));
    
  xsh_msg("method %s", flat_method);

  if ( strcmp( flat_method, "master") == 0){
    check( div_frame = xsh_divide_flat( rmbkg, masterflat_frame, 
      tag, instrument));
  }
  else{
    xsh_msg("---Create blaze image");
    check( blaze_frame = xsh_blaze_image( masterflat_frame, order_tab_edges,
     instrument));
    check( div_frame = xsh_divide_by_blaze( rmbkg, blaze_frame, instrument));
  }
  
  sprintf( geom_prefix, "orig_%s", rec_prefix);
  /* Rectify object */
  for( i=1; i<= geom_niter; i++){
    xsh_free_frameset( &rect_frameset);
    xsh_free_frameset( &rect_frameset_eso);
    xsh_free_frameset( &rect_frameset_tab) ;
    xsh_free_frameset( &merge_frameset);
    xsh_free_frameset( &locifu_frameset);

    xsh_msg( "---Do rectify for ifu: iteration %d/%d", i, geom_niter);
      
    rect_frameset_eso=cpl_frameset_new();
    rect_frameset_tab=cpl_frameset_new();

    check( rect_frameset = xsh_rectify_ifu( div_frame, order_tab_edges,
      wave_tabs_ifu, shiftifu_old_frameset, model_config_frame, 
      instrument, rectify_par, 
      spectralformat_frame, slitmap_frame, 
      &rect_frameset_eso, &rect_frameset_tab, geom_prefix));

    /* Merge each slitlet */
    check( merge_frameset = xsh_merge_ord_ifu( rect_frameset,
      instrument, merge_par, geom_prefix)); 

    /* Localize ifu */
    check( locifu_frameset = xsh_localize_ifu( merge_frameset,
      skymask_frame, loc_ifu_par, instrument, geom_prefix));
    
    /* Compute the shift */
    check( shiftifu_frameset = xsh_compute_shift_ifu( lambda_ref,
      lambdaref_hsize, 
      locifu_frameset, shiftifu_old_frameset, instrument, rec_prefix));

    xsh_free_frameset( &shiftifu_old_frameset);
    shiftifu_old_frameset = shiftifu_frameset;
    sprintf( geom_prefix, "%s", rec_prefix);
  }

  /* Building 3D (data cube) */
  if ( do_cube){
    xsh_free_frameset( &rect_frameset);
    xsh_free_frameset( &rect_frameset_eso);
    xsh_free_frameset( &rect_frameset_tab) ;
    xsh_free_frameset( &merge_frameset);
    xsh_free_frameset( &locifu_frameset);
    
    rect_frameset_eso=cpl_frameset_new();
    rect_frameset_tab=cpl_frameset_new();

    check( rect_frameset = xsh_rectify_ifu( div_frame, order_tab_edges,
      wave_tabs_ifu, shiftifu_frameset, model_config_frame, 
      instrument, rectify_par, 
      spectralformat_frame, slitmap_frame, 
      &rect_frameset_eso, &rect_frameset_tab, rec_prefix));

    /* Merge each slitlet */
    check( merge_frameset = xsh_merge_ord_ifu( rect_frameset,
      instrument, merge_par, rec_prefix)); 
    /* build cube */  
    check( data_cube = xsh_cube( merge_frameset, instrument, rec_prefix));
  }
  
  /* Save recipe products */
  xsh_msg( "---Save products");

  for( i = 0 ; i<3 ; i++ ) {
    cpl_frame *shiftifu_frame = NULL;

    check( shiftifu_frame = cpl_frameset_get_frame( shiftifu_frameset, i));
    check( xsh_add_product_table( shiftifu_frame, frameset,parameters, 
				  RECIPE_ID, instrument,NULL));
  }


  if ( do_cube){
    const char* name=NULL;
    cpl_propertylist* plist=NULL;
    int naxis2=0;
    int save_size=0;
    const int peack_search_hsize=5;
    int method=0;
    cpl_frame* qc_trace_frame=NULL;
    
    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));
       }
       xsh_free_frame(&qc_trace_frame);
    }
  		 
  cleanup:
    xsh_end( RECIPE_ID, frameset, parameters);
    XSH_FREE( rec_prefix);

    XSH_FREE( crh_clipping_par);
    XSH_FREE( backg_par);
    XSH_FREE( crh_single_par);
    XSH_FREE( rectify_par);
    XSH_FREE( stack_par);

    XSH_FREE( loc_ifu_par);
    xsh_instrument_free( &instrument);

    xsh_free_frameset( &raws);
    xsh_free_frameset( &calib);
    xsh_free_frameset( &wave_tabs_ifu);

    xsh_free_frame( &crhm_frame ) ;
    xsh_free_frame( &rmbias);
    xsh_free_frame( &rmdark);
    xsh_free_frame( &rmbkg);
    xsh_free_frame( &blaze_frame);
    xsh_free_frame( &div_frame);

    xsh_free_frameset( &rect_frameset);
    xsh_free_frameset( &rect_frameset_eso);
    xsh_free_frameset( &rect_frameset_tab) ;
    xsh_free_frameset( &merge_frameset);
    xsh_free_frameset( &locifu_frameset);
    xsh_free_frameset( &shiftifu_frameset);
    xsh_free_frame( &clean_frame);
    xsh_free_frame( &grid_backg);
    xsh_free_frame( &frame_backg);
    xsh_free_frame( &data_cube);
    return;
}

/**@}*/
