/*                                                                          *
 *   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: 2012-12-07 16:51:34 $
 * $Revision: 1.4 $
 */

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

/*-------------------------------------------------------------------------*/
/**
 * @defgroup test_xsh_guess Predict X,Y as function of input ord,lam,s
 * @ingroup unit_tests
 * 
 */
/*-------------------------------------------------------------------------*/
/**@{*/

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

#include <tests.h>

#include <xsh_error.h>
#include <xsh_msg.h>
#include <xsh_data_instrument.h>
#include <xsh_drl.h>
#include <xsh_model_io.h>
#include <xsh_data_the_map.h>
#include <xsh_pfits.h>

#include <cpl.h>
#include <math.h>

#include <getopt.h>

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

#define MODULE_ID "XSH_GUESS"
#define SYNTAX "Test X,Y point generation\n"\
  "use : ./the_xsh_guess XSH_MODEL_CFG INPUT_MODEL_TAB (columns 'order', 'wavelength', 'slit')\n"\
  "(table with predicted 'x','y' predicted positions)\n"

  
/*--------------------------------------------------------------------------
  Implementation
  --------------------------------------------------------------------------*/

/**
  @brief
    Unit test of xsh_themap
  @return
    0 if success

*/
int main( int argc, char **argv)
{
  /* Declarations */
  int ret = 0 ;
  const char* tag=NULL;
  char* model_cfg_name = NULL;
  char* input_tab_name = NULL;
  cpl_propertylist* plist=NULL;
  cpl_frame* model_cfg_frame = NULL;
  cpl_frame* the_map_frame = NULL;
  xsh_the_map* the_map_list=NULL;
  int i = 0;
  FILE* themap_file = NULL;
  xsh_xs_3 model_config ;
  int binx=1;
  int biny=1;
  cpl_table* the_map_tab=NULL;
  int* pord=NULL;
  float* pwav=NULL;
  int* ps=NULL;
  int nrow=0;
  double x=0;
  double y=0;
  xsh_instrument* inst;
  /* Initialize libraries */
  TESTS_INIT(MODULE_ID);

  cpl_msg_set_level(CPL_MSG_DEBUG);
  xsh_debug_level_set(XSH_DEBUG_LEVEL_MEDIUM) ;

  /* Analyse parameters */
  if (argc > 1){
    model_cfg_name = argv[1];
    input_tab_name = argv[2];
  }
  else{
    printf(SYNTAX);
    return 0;  
  }
  
  /* Create frames */
  XSH_ASSURE_NOT_NULL( model_cfg_name);
  plist=cpl_propertylist_load(model_cfg_name,0);
  tag=xsh_pfits_get_pcatg(plist);

  check(model_cfg_frame = cpl_frame_new());
  cpl_frame_set_filename( model_cfg_frame, model_cfg_name) ;
  cpl_frame_set_level( model_cfg_frame, CPL_FRAME_LEVEL_TEMPORARY);
  cpl_frame_set_group( model_cfg_frame, CPL_FRAME_GROUP_RAW ) ;
  cpl_frame_set_type( model_cfg_frame, CPL_FRAME_TYPE_TABLE ) ;
  check(cpl_frame_set_tag( model_cfg_frame, tag ) );

  xsh_msg("model_cfg_name=%s",model_cfg_name);
  xsh_msg("input_tab_name=%s",input_tab_name);
 
  inst=xsh_instrument_new();
  check(xsh_instrument_parse_tag(inst,tag));
  check( xsh_model_config_load_best( model_cfg_frame, &model_config));
  xsh_model_binxy(&model_config,binx,biny);
  the_map_tab=cpl_table_load(input_tab_name,1,0);
 
  check(pwav=cpl_table_get_data_float(the_map_tab,XSH_THE_MAP_TABLE_COLNAME_WAVELENGTH));
  check(pord=cpl_table_get_data_int(the_map_tab,XSH_THE_MAP_TABLE_COLNAME_ORDER));
  check(ps=cpl_table_get_data_int(the_map_tab,XSH_THE_MAP_TABLE_COLNAME_SLITINDEX));

  nrow=cpl_table_get_nrow(the_map_tab);
  for(i=0;i<nrow;i++) {
     check(xsh_model_get_xy(&model_config,inst,pwav[i],pord[i],ps[i],&x,&y));
  }
  xsh_free_table(&the_map_tab);
 

  /* Create DS9 REGION FILE */
  themap_file = fopen( "THEMAP.reg", "w");
  fprintf( themap_file, "# Region file format: DS9 version 4.0\n\
    global color=red font=\"helvetica 4 normal\"\
    select=1 highlite=1 edit=1 move=1 delete=1 include=1 fixed=0 source \nimage\n");


  the_map_frame = cpl_frame_new();
  cpl_frame_set_filename( the_map_frame, input_tab_name) ;
  cpl_frame_set_level( the_map_frame, CPL_FRAME_LEVEL_TEMPORARY);
  cpl_frame_set_group( the_map_frame, CPL_FRAME_GROUP_RAW ) ;
  cpl_frame_set_type( the_map_frame, CPL_FRAME_TYPE_TABLE ) ;
  cpl_frame_set_tag( the_map_frame, tag ) ;

  the_map_list=xsh_the_map_load(the_map_frame);

  int themap_size=nrow;
  for( i=0; i<themap_size; i++){
    float lambdaTHE = 0.0;
    double xd, yd, slit; 

    check(lambdaTHE = xsh_the_map_get_wavelength(the_map_list, i));

    check(xd = xsh_the_map_get_detx(the_map_list, i));
    check(yd = xsh_the_map_get_dety(the_map_list, i));
    check(slit = (double) xsh_the_map_get_slit_position( the_map_list, i));
    if (slit == 0){
      fprintf( themap_file, "point(%f,%f) #point=cross color=yellow "\
        "font=\"helvetica 10 normal\"  text={THE %.3f}\n", xd, yd, lambdaTHE);
    }
    else{
      fprintf( themap_file, "point(%f,%f) #point=cross color=yellow "\
        "font=\"helvetica 10 normal\"  text={slit %f}\n", xd, yd, slit);
    }
  }



  cleanup:
  xsh_free_propertylist(&plist);
  xsh_the_map_free(&the_map_list);
  xsh_free_table(&the_map_tab);
  xsh_free_frame(&the_map_frame);
  xsh_free_frame(&model_cfg_frame);
  xsh_instrument_free(&inst);
  if(themap_file != NULL) {
     fclose( themap_file);
  }
  if (cpl_error_get_code() != CPL_ERROR_NONE) {
     xsh_error_dump(CPL_MSG_ERROR);
     ret = -1;
  }
  return ret ;
}

/**@}*/
