/*                                                                            *
 *   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.6 $
 * $Name: not supported by cvs2svn $
 */
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

/*--------------------------------------------------------------------------*/
/**
 * @defgroup test_xsh_test_order     Test Data type ORDER functions
 * @ingroup unit_tests
 *
 */
/*--------------------------------------------------------------------------*/
/**@{*/

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


#include <xsh_data_order.h>
#include <xsh_error.h>
#include <xsh_msg.h>
#include <xsh_data_instrument.h>
#include <xsh_dfs.h>
#include <xsh_pfits.h>
#include <tests.h>
#include <xsh_data_spectralformat.h>
#include <xsh_data_arclist.h>
#include <xsh_data_wavesol.h>
#include <xsh_utils_table.h>
#include <cpl.h>
#include <math.h>
#include <getopt.h>

/*---------------------------------------------------------------------------
                            Defines
 ---------------------------------------------------------------------------*/
#define MODULE_ID "XSH_DATA_WAVE_TAB_2D_SAMPLE"

#define SYNTAX "Test the wave tab 2d\n"\
  "usage : ./the_xsh_data_wave_tab_2d [OPTIONS] WAVE_TAB_2D ARC_LIST SPECTRAL_FORMAT\n"\
  "WAVE_TAB_2D     => The wave tab 2d\n"\
  "ARC_LIST        => An arclist\n"\
  "SPECTRAL_FORMAT => The spectral format\n"\
  "OPTIONS => :\n"\
  " --slit-step=<nn>    : Step in slit. Default 0.2 \n"


static const char * Options = "";

enum {
  SLIT_STEP_OPT
} ;

static float slit_step = 1.4;


static struct option LongOptions[] = {
  {"slit-step", required_argument, 0, SLIT_STEP_OPT},
  {NULL, 0, 0, 0}
} ;

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

static void HandleOptions( int argc, char ** argv)
{
  int opt ;
  int option_index = 0;

  while( (opt = getopt_long( argc, argv, Options,
			     LongOptions, &option_index )) != EOF )
    switch( opt ) {
    case SLIT_STEP_OPT:
      slit_step = atof(optarg);
      break ;
    default:
      printf( SYNTAX ) ;
      exit( 0 ) ;
    }
}

/*--------------------------------------------------------------------------*/
/**
  @brief
    Unit test of xsh_data_wave_tab_2d
  @return
    0 if success

*/
/*--------------------------------------------------------------------------*/
int main(int argc, char** argv)
{
  int ret = 0;
  int i;
  float j,k;
  xsh_instrument * instrument = NULL ;
  //  XSH_INSTRCONFIG* iconfig = NULL;

  char* wave_tab_2d_name = NULL;
  cpl_frame *wave_tab_2d_frame = NULL;
  char* spectralformat_name = NULL;
  cpl_frame *spectralformat_frame = NULL;
  char* arclist_name = NULL;
  cpl_frame *arclist_frame = NULL;
  xsh_spectralformat_list *spec_list = NULL;
  xsh_wavesol *wave_tab_2d = NULL;
  FILE* wave_tab_2d_file = NULL;
  FILE* wave_tab_2d_dat_file = NULL;
  xsh_arclist *arclist = NULL;


  /* Initialize libraries */
  TESTS_INIT(MODULE_ID);
  cpl_msg_set_level(CPL_MSG_DEBUG);
  xsh_debug_level_set(XSH_DEBUG_LEVEL_MEDIUM) ;

  HandleOptions( argc, argv);

  /* Analyse parameters */
  if ( (argc-optind) == 3) {
    wave_tab_2d_name = argv[optind++];
    arclist_name = argv[optind++];
    spectralformat_name = argv[optind++];
  }
  else{
    printf(SYNTAX);
    return 0;
  }
  xsh_msg("Wave tab 2d : %s", wave_tab_2d_name);
  xsh_msg("Arclist : %s", arclist_name);
  xsh_msg("Spectral format : %s", spectralformat_name);
  xsh_msg(" Options : slit-step %f", slit_step);

  /* Create frames */
  XSH_ASSURE_NOT_NULL( wave_tab_2d_name);
  wave_tab_2d_frame = cpl_frame_new();
  cpl_frame_set_filename( wave_tab_2d_frame, wave_tab_2d_name) ;
  cpl_frame_set_level( wave_tab_2d_frame, CPL_FRAME_LEVEL_TEMPORARY);
  cpl_frame_set_group( wave_tab_2d_frame, CPL_FRAME_GROUP_RAW);

  XSH_ASSURE_NOT_NULL( arclist_name);
  arclist_frame = cpl_frame_new();
  cpl_frame_set_filename( arclist_frame, arclist_name) ;
  cpl_frame_set_level( arclist_frame, CPL_FRAME_LEVEL_TEMPORARY);
  cpl_frame_set_group( arclist_frame, CPL_FRAME_GROUP_RAW);

  XSH_ASSURE_NOT_NULL( spectralformat_name);
  spectralformat_frame = cpl_frame_new();
  cpl_frame_set_filename( spectralformat_frame, spectralformat_name) ;
  cpl_frame_set_level( spectralformat_frame, CPL_FRAME_LEVEL_TEMPORARY);
  cpl_frame_set_group( spectralformat_frame, CPL_FRAME_GROUP_RAW);

  instrument = xsh_instrument_new();
  check( spec_list = xsh_spectralformat_list_load( spectralformat_frame,
    instrument));
  check( wave_tab_2d = xsh_wavesol_load( wave_tab_2d_frame, instrument));
  xsh_msg("Wavesol lambda (%f,%f)", wave_tab_2d->min_lambda, 
    wave_tab_2d->max_lambda);
  xsh_msg("Wavesol order (%f,%f)", wave_tab_2d->min_order,
    wave_tab_2d->max_order);
  xsh_msg("Wavesol slit (%f,%f)", wave_tab_2d->min_slit,
    wave_tab_2d->max_slit);

  wave_tab_2d_file = fopen( "WAVE_TAB_2D_sample.reg", "w");
  wave_tab_2d_dat_file = fopen( "WAVE_TAB_2D_sample.dat", "w");

  fprintf( wave_tab_2d_file, "# Region file format: DS9 version 4.0\n"\
    "global color=red font=\"helvetica 10 normal\""\
    "select=1 highlite=1 edit=1 move=1 delete=1 include=1 fixed=0 "\
    "source\nimage\n");
  fprintf( wave_tab_2d_dat_file, "# x y lambda slit\n");

  check( arclist = xsh_arclist_load( arclist_frame));

  for( i=0; i< arclist->size; i++){
    double absorder;
    float lambda;
    cpl_vector* orders = NULL;
    int nb_orders;

    check( lambda = xsh_arclist_get_wavelength( arclist, i));
    check( orders = xsh_spectralformat_list_get_orders( spec_list, lambda));
    if (orders != NULL){
      check( nb_orders = cpl_vector_get_size( orders));
    }
    else{
      nb_orders = 0;
    }
    for(j=0; j < nb_orders; j++){
      double x, y;
      absorder= cpl_vector_get( orders, j);
      xsh_msg("order %f lambda %f", absorder, lambda);
      check( x = xsh_wavesol_eval_polx( wave_tab_2d, lambda, absorder, 0.0));
      check( y = xsh_wavesol_eval_poly( wave_tab_2d, lambda, absorder, 0.0));
      fprintf( wave_tab_2d_file, "point(%f,%f) #point=cross color=red font="\
            "\"helvetica 10 normal\" text={ %.3f}\n", x, y, lambda);
      fprintf( wave_tab_2d_dat_file,"%f %f %f %f\n", x, y , lambda, 0.0);
/*
      for( k=wave_tab_2d->min_slit; k <= (wave_tab_2d->max_slit+0.00001); k+=slit_step){
        check( x = xsh_wavesol_eval_polx( wave_tab_2d, lambda, absorder, k));
        check( y = xsh_wavesol_eval_poly( wave_tab_2d, lambda, absorder, k));
        fprintf( wave_tab_2d_file, "point(%f,%f) #point=cross color=green font="\
            "\"helvetica 10 normal\" text={ %.3f}\n", x, y, k);
      }
*/
      for( k=wave_tab_2d->min_slit; k <= (wave_tab_2d->max_slit+0.00001-slit_step); k+=slit_step){
        double x1,x2,y1,y2;
        check( x1 = xsh_wavesol_eval_polx( wave_tab_2d, lambda, absorder, k));
        check( y1 = xsh_wavesol_eval_poly( wave_tab_2d, lambda, absorder, k));
        check( x2 = xsh_wavesol_eval_polx( wave_tab_2d, lambda, absorder, k+slit_step));
        check( y2 = xsh_wavesol_eval_poly( wave_tab_2d, lambda, absorder, k+slit_step));
        fprintf( wave_tab_2d_file, "line(%f,%f,%f,%f) #color=green font="\
            "\"helvetica 10 normal\"\n", x1, y1, x2, y2);
        fprintf( wave_tab_2d_dat_file,"%f %f %f %f\n", x, y , lambda, k);
      }
    }
  } 

  cleanup:
    if (cpl_error_get_code() != CPL_ERROR_NONE) {
      xsh_error_dump(CPL_MSG_ERROR);
      ret  = 1;
    }
    if ( NULL !=  wave_tab_2d_file) {
      fclose( wave_tab_2d_file);
    }
    if ( NULL !=  wave_tab_2d_dat_file) {
      fclose( wave_tab_2d_dat_file);
    }

    return ret ;
}

/**@}*/
