/*                                                                              *
 *   This file is part of the ESO UVES Pipeline                                 *
 *   Copyright (C) 2004,2005 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-01-17 07:53:20 $
 * $Revision: 1.8 $
 * $Name: not supported by cvs2svn $
 * $Log: not supported by cvs2svn $
 * Revision 1.7  2010/02/08 07:11:39  amodigli
 * added test_load_3dtable
 *
 * Revision 1.6  2009/06/05 05:49:02  amodigli
 * updated init/end to cpl5
 *
 * Revision 1.5  2008/09/29 07:02:05  amodigli
 * add #include <string.h>
 *
 * Revision 1.4  2007/05/23 06:43:23  jmlarsen
 * Removed unused variables
 *
 * Revision 1.3  2007/04/24 12:50:29  jmlarsen
 * Replaced cpl_propertylist -> uves_propertylist which is much faster
 *
 * Revision 1.2  2007/03/20 07:28:02  jmlarsen
 * Test TYPE = 'NULL'
 *
 * Revision 1.1  2007/03/15 12:27:18  jmlarsen
 * Moved unit tests to ./uves/tests and ./flames/tests
 *
 * Revision 1.2  2007/02/27 14:04:14  jmlarsen
 * Move unit test infrastructure to IRPLIB
 *
 * Revision 1.1  2007/02/21 12:38:26  jmlarsen
 * Renamed _test -> -test
 *
 * Revision 1.22  2007/01/29 12:17:54  jmlarsen
 * Support setting verbosity from command line
 *
 * Revision 1.21  2006/11/24 09:39:35  jmlarsen
 * Factored out termination code
 *
 * Revision 1.20  2006/11/16 09:49:25  jmlarsen
 * Fixed doxygen bug
 *
 * Revision 1.19  2006/11/08 14:03:59  jmlarsen
 * Doxybugfix
 *
 * Revision 1.18  2006/11/07 13:59:19  jmlarsen
 * Removed memory leaks
 *
 * Revision 1.17  2006/11/06 15:31:52  jmlarsen
 * Added check for memory leak
 *
 * Revision 1.16  2006/11/06 15:30:54  jmlarsen
 * Added missing includes
 *
 * Revision 1.15  2006/11/06 15:19:41  jmlarsen
 * Removed unused include directives
 *
 * Revision 1.14  2006/11/03 15:15:46  jmlarsen
 * Added test of uves_align
 *
 * Revision 1.16  2006/09/11 13:59:01  jmlarsen
 * Renamed identifier reserved by POSIX
 *
 */

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

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

#include <uves_response_utils.h>
#include <uves_utils_wrappers.h>
#include <uves_pfits.h>
#include <uves_error.h>
#include <uves_msg.h>

#include <cpl_test.h>
#include <cpl.h>
#include <string.h>
/*-----------------------------------------------------------------------------
                                Defines
 -----------------------------------------------------------------------------*/

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

/*----------------------------------------------------------------------------*/
/**
 * @defgroup uves_response_test   Response recipe related unit tests
 */
/*----------------------------------------------------------------------------*/
/**@{*/
/*----------------------------------------------------------------------------*/
/**
  @brief   Test of uves_align
**/
/*----------------------------------------------------------------------------*/
static void
test_load_3dtable(void)
{
   cpl_table *flux_table = NULL;
   const char* dir_name="/media/VERBATIM/data7/flames/flames_uves_demo/ref/";
   const char* tab_name="flxstd.fits";
   char res_name[80];
   char ref_name[25];
   char ref_type[25];

   char full_name[256];
   int nraws=0;
   int i=0;
   double ref_ra=0;
   double ref_dec=0;
   uves_propertylist* header=NULL;
   const char *columns[3] = {"LAMBDA", "BIN_WIDTH", "F_LAMBDA"};
   int ndata;                      /* Number of elements in column */
   int j=0;
   cpl_table* result=NULL;
   sprintf(full_name,"%s%s",dir_name,tab_name);
   uves_msg("full name: %s",full_name);
   flux_table=cpl_table_load(full_name,1,0);
   nraws=cpl_table_get_nrow(flux_table);
   header=uves_propertylist_load(full_name,0);

   uves_msg("std: name \t type \t ra \t dec");
   for(i=0;i<nraws; i++) {

     check( ref_ra  = cpl_table_get_double(flux_table, "RA_DEG", i, NULL),
	    "Could not read catalogue star right ascension");

     check( ref_dec = cpl_table_get_double(flux_table, "DEC_DEG", i, NULL),
	    "Could not read catalogue star declination");

     check( sprintf(ref_name, cpl_table_get_string(flux_table, "OBJECT", i)),
		    "Could not read reference object name");
    
     check( sprintf(ref_type,cpl_table_get_string(flux_table, "TYPE", i)),
	    "Could not read reference object type");

     uves_msg("std: %s \t %s \t %f \t %f",ref_name,ref_type,ref_ra,ref_dec);

     sprintf(res_name,"%s.fits",ref_name);
     check( ndata = cpl_table_get_int(flux_table, "NDATA", i, NULL),
	    "Error reading length of flux array");

     result=cpl_table_new(ndata);
     for(j = 0; j < 3; j++)
       {
	 const cpl_array *data;
	 int indx;
        
	 cpl_table_new_column(result, columns[j], CPL_TYPE_DOUBLE);
        
	 data = cpl_table_get_array(flux_table, columns[j], i);

	 /* Only the 'ndata' first elements of the array are used,
	    and the array may be longer than this */
	 uves_msg_debug("3d table array size = %" CPL_SIZE_FORMAT ", ndata = %d",
			cpl_array_get_size(data), ndata);

	 assure( cpl_array_get_size(data) >= ndata,
		 CPL_ERROR_ILLEGAL_INPUT,
		 "Flux table row %d: column '%s' depth (%" CPL_SIZE_FORMAT ") "
		 "is less than NDATA (%d)",
		 i, columns[j], cpl_array_get_size(data), ndata);

	 for (indx = 0; indx < ndata; indx++)
	   {
	     /* 3d columns are float */
	     cpl_table_set_double(result, columns[j], indx, 
				  cpl_array_get_float(data, indx, NULL));
	   }
       }
     
     uves_table_save(result, header, NULL,res_name, CPL_IO_DEFAULT);
     uves_free_table(&result);
   }
  

  cleanup:
   uves_free_table(&flux_table);
   uves_free_propertylist(&header);

  return;
}

/*----------------------------------------------------------------------------*/
/**
  @brief   Test of uves_align
**/
/*----------------------------------------------------------------------------*/
static void
test_3dtable(void)
{
    /* Create flux table + header */
    cpl_table *flux_table = NULL;
    uves_propertylist *raw_header = NULL;
    cpl_array *values = NULL;
    int depth = 10;
    int nrow = 2;
    const char *object[] = {"first std", "another standard star"};
    const char *type  [] = {"NULL", "type 2"};
    const double lambda[] = {8000, 2000};
    const double fluxes[] = {1000000, 200};
    const double bin_width[] = {0.8, 0.0003};
    const double ra[] = {10, 80};
    const double dec[] = {-8, 0};

    cpl_table *cat_flux = NULL;
    char *ref_name = NULL;

    int i;

    /* Create flux table */
    flux_table = cpl_table_new(nrow);

    cpl_table_new_column(flux_table, "RA_DEG", CPL_TYPE_DOUBLE);
    cpl_table_new_column(flux_table, "DEC_DEG", CPL_TYPE_DOUBLE);

    cpl_table_new_column(flux_table, "OBJECT", CPL_TYPE_STRING);
    cpl_table_new_column(flux_table, "TYPE", CPL_TYPE_STRING);

    cpl_table_new_column(flux_table, "NDATA", CPL_TYPE_INT); /* depth of arrays */

    cpl_table_new_column_array(flux_table, "LAMBDA", CPL_TYPE_FLOAT, depth);
    cpl_table_new_column_array(flux_table, "BIN_WIDTH", CPL_TYPE_FLOAT, depth);
    cpl_table_new_column_array(flux_table, "F_LAMBDA", CPL_TYPE_FLOAT, depth);

    values = cpl_array_new(depth, CPL_TYPE_FLOAT);

    for (i = 0; i < nrow; i++)
	{
	    cpl_table_set_double(flux_table, "RA_DEG", i, ra[i]); 
	    cpl_table_set_double(flux_table, "DEC_DEG", i, dec[i]);
	    cpl_table_set_string(flux_table, "OBJECT", i, object[i]);
	    cpl_table_set_string(flux_table, "TYPE", i, type[i]);
	    cpl_table_set_int   (flux_table, "NDATA", i, depth);

	    cpl_array_fill_window_float(values, 0, depth, lambda[i]); 
	    cpl_table_set_array(flux_table, "LAMBDA", i, values);

	    cpl_array_fill_window_float(values, 0, depth, bin_width[i]); 
	    cpl_table_set_array(flux_table, "BIN_WIDTH", i, values);

	    cpl_array_fill_window_float(values, 0, depth, fluxes[i]); 
	    cpl_table_set_array(flux_table, "F_LAMBDA", i, values);
	}

    /* Create header */
    raw_header = uves_propertylist_new();

    /* Set RA, DEC to match each row of flux table, and verify that
       we got the corresponding std star */
    for (i = 0; i < nrow; i++)
	{
	    double paccuracy = 60; /* arcsecs */
	    double residual = 30;
	    
	    uves_pfits_set_ra (raw_header, ra[i]+residual/3600);
	    uves_pfits_set_dec(raw_header, dec[i]-residual/3600);
	    
	    uves_free_table(&cat_flux);
	    cpl_free(ref_name); ref_name = NULL;
	    check_nomsg( cat_flux = uves_align(raw_header,
					       flux_table,
					       paccuracy,
					       &ref_name));

	    /* Saving table string values to FITS might add trailing blanks;
	       replace with end-of-string */
	    while(ref_name[strlen(ref_name)-1] == ' ')
		{
		    /* O(n^2) but that is okay */
		    ref_name[strlen(ref_name)-1] = '\0';
		}

	    /* cpl_table_dump(cat_flux, 0, cpl_table_get_nrow(cat_flux), stdout); */
	    
	    assure( cpl_table_get_nrow(cat_flux) == depth, CPL_ERROR_ILLEGAL_OUTPUT,
		    "Flux table has %" CPL_SIZE_FORMAT " rows, %d expected",
		    cpl_table_get_nrow(cat_flux), depth);
	    
	    assure( strcmp(ref_name, object[i]) == 0, CPL_ERROR_ILLEGAL_OUTPUT,
		    "Found '%s'; Expected '%s'", ref_name, object[i]);
	    
#if 0
	    assure( float_equal(cpl_table_get_column_mean(cat_flux, "LAMBDA"), 
				lambda[i], 0.001),
		    CPL_ERROR_ILLEGAL_OUTPUT,
		    "LAMBDA = %f; Expected = %f", 
		    cpl_table_get_column_mean(cat_flux, "LAMBDA"), lambda[i]);
	    
	    assure( float_equal(cpl_table_get_column_mean(cat_flux, "BIN_WIDTH"), 
				bin_width[i], 0.001),
		    CPL_ERROR_ILLEGAL_OUTPUT,
		    "BIN_WIDTH = %f; Expected = %f", 
		    cpl_table_get_column_mean(cat_flux, "BIN_WIDTH"), bin_width[i]);
	    
	    assure( float_equal(cpl_table_get_column_mean(cat_flux, "F_LAMBDA"), 
				fluxes[i], 0.001),
		    CPL_ERROR_ILLEGAL_OUTPUT,
		    "F_LAMBDA = %f; Expected = %f", 
		    cpl_table_get_column_mean(cat_flux, "F_LAMBDA"), fluxes[i]);
#endif
	    cpl_test_rel(cpl_table_get_column_mean(cat_flux, "LAMBDA"), 
                            lambda[i], 0.001);
	    
	    cpl_test_rel(cpl_table_get_column_mean(cat_flux, "BIN_WIDTH"), 
                            bin_width[i], 0.001);
	    
	    cpl_test_rel(cpl_table_get_column_mean(cat_flux, "F_LAMBDA"),
                            fluxes[i], 0.001);
	}
    
  cleanup:
    uves_free_table(&flux_table);
    uves_free_table(&cat_flux);
    uves_free_array(&values);
    uves_free_propertylist(&raw_header);
    cpl_free(ref_name);

    
    return;
}

/*----------------------------------------------------------------------------*/
/**
  @brief   Test 3d table usage in uves_align
**/
/*----------------------------------------------------------------------------*/

int main(void)
{
    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);

    check_nomsg( test_3dtable() );
    //check_nomsg( test_load_3dtable() );

  cleanup:
    return cpl_test_end(0);
}

/**@}*/
