/*                                                                          *
 *   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-08-23 12:00:20 $
 * $Revision: 1.15 $
 */

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

/*-------------------------------------------------------------------------*/
/**
 * @defgroup test_xsh_resid_tab  Test a Residual tab
 * @ingroup unit_tests
 * 
 */
/*-------------------------------------------------------------------------*/
/**@{*/

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

#include <tests.h>

#include <xsh_data_pre.h>
#include <xsh_error.h>
#include <xsh_msg.h>
#include <xsh_data_instrument.h>
#include <xsh_data_resid_tab.h>
#include <xsh_drl.h>
#include <xsh_pfits.h>

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

#include <getopt.h>

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

#define MODULE_ID "XSH_RESID_TAB"
#define SYNTAX "Test the residual tab\n"\
  "use : ./the_xsh_resid_tab RESID_TAB \n"\
  "RESID_TAB   => the residual table\n"

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

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

*/
int main( int argc, char **argv)
{
  /* Declarations */
  int ret = 0 ;
  xsh_instrument* instrument = NULL;

  char* resid_tab_name = NULL;
  const char* extracted_tab_name = "redid_not_flagged.fits";
  cpl_frame* resid_tab_frame = NULL;
  xsh_resid_tab* resid_tab = NULL;
  int resid_tab_size = 0;
  cpl_table* tab_flagged=NULL;
  cpl_table* tab_extract=NULL;
  cpl_propertylist* plist=NULL;
  int i = 0;
  FILE* resid_tab_the_file = NULL;

  /* 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){
    resid_tab_name = argv[1];
  }
  else{
    printf(SYNTAX);
    TEST_END();
    return 0;  
  }
  
  /* Create instrument structure and fill */
  instrument = xsh_instrument_new() ;
  xsh_instrument_set_mode( instrument, XSH_MODE_IFU );
  xsh_instrument_set_arm( instrument, XSH_ARM_VIS);


  XSH_ASSURE_NOT_NULL( resid_tab_name);
  tab_flagged=cpl_table_load(resid_tab_name,1,0);
  plist=cpl_propertylist_load(resid_tab_name,0);
  cpl_table_and_selected_int(tab_flagged,"Flag",CPL_EQUAL_TO,0);
  tab_extract=cpl_table_extract_selected(tab_flagged);
  cpl_table_erase_column(tab_extract,"Flag");
  cpl_table_save(tab_extract,plist,NULL,extracted_tab_name,CPL_IO_DEFAULT);

  /* Create frames */
  resid_tab_frame = cpl_frame_new();
  cpl_frame_set_filename( resid_tab_frame, extracted_tab_name) ;
  cpl_frame_set_level( resid_tab_frame, CPL_FRAME_LEVEL_TEMPORARY);
  cpl_frame_set_group( resid_tab_frame, CPL_FRAME_GROUP_RAW ) ;

  check( resid_tab = xsh_resid_tab_load( resid_tab_frame));
  check( resid_tab_size = xsh_resid_tab_get_size( resid_tab));

  /* Create DS9 REGION FILE */
  xsh_msg("Save residual tab in RESID_TAB.reg");
  resid_tab_the_file = fopen( "RESID_TAB.reg", "w");

  fprintf( resid_tab_the_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( resid_tab_the_file, "# RED the_x the_y (pixels)\n"\
    "# MAGENTA corr_x corr_y (pixels)\n"\
    "# GREEN gauss_x gauss_y (pixels)\n"\
    "# BLUE poly_x poly_y (pixels)\n");

  if (resid_tab->solution_type == XSH_DETECT_ARCLINES_TYPE_POLY){
    xsh_msg("Residual tab compute from POLYNOMIAL");
  }
  else{
    xsh_msg("Residual tab compute from PHYSICAL MODEL");
  }
  for( i=0; i<resid_tab_size; i++){
    double the_x, the_y;
    double corr_x, corr_y;
    double gauss_x, gauss_y;
    double poly_x, poly_y;
    double lambda;   
 
    lambda = resid_tab->lambda[i];
    the_x = resid_tab->thpre_x[i];
    the_y = resid_tab->thpre_y[i];
    corr_x = resid_tab->thcor_x[i];
    corr_y = resid_tab->thcor_y[i];
    gauss_x = resid_tab->xgauss[i];
    gauss_y = resid_tab->ygauss[i];
    if (resid_tab->solution_type == XSH_DETECT_ARCLINES_TYPE_POLY){
      poly_x = resid_tab->xpoly[i];
      poly_y = resid_tab->ypoly[i];
    }
    else{
      poly_x = resid_tab->thanneal_x[i];
      poly_y = resid_tab->thanneal_y[i];
    }
    fprintf( resid_tab_the_file, "point(%f,%f) #point=cross color=red text={THE %.3f} font="\
      "\"helvetica 10 normal\"\n", the_x, the_y, lambda);
    fprintf( resid_tab_the_file, "point(%f,%f) #point=diamond color=magenta font="\
      "\"helvetica 4 normal\"\n", corr_x, corr_y);
    fprintf( resid_tab_the_file, "point(%f,%f) #point=circle color=green font="\
      "\"helvetica 4 normal\"\n", gauss_x, gauss_y);
    fprintf( resid_tab_the_file, "point(%f,%f) #point=x color=blue font="\
      "\"helvetica 4 normal\"\n", poly_x, poly_y);
  }
  fclose( resid_tab_the_file);
  xsh_msg( "Save residual tab in RESID_TAB.dat");
  check( xsh_resid_tab_log( resid_tab, "RESID_TAB.dat"));

  cleanup:
    xsh_instrument_free( &instrument);
    xsh_free_frame (&resid_tab_frame);
    xsh_resid_tab_free( &resid_tab);
    xsh_free_table(&tab_extract);
    xsh_free_propertylist(&plist);

    if (cpl_error_get_code() != CPL_ERROR_NONE) {
      xsh_error_dump(CPL_MSG_ERROR);
      ret = 1;
    }
    TEST_END();
    return ret ;
}

/**@}*/
