/*
 * This file is part of the ESO UVES Pipeline
 * Copyright (C) 2004,2005 European Southern Observatory
 *
 * This program 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-04-16 15:35:24 $
 * $Revision: 1.121 $
 * $Name: not supported by cvs2svn $
 *
 */
#ifndef UVES_UTILS_H
#define UVES_UTILS_H


#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif
#include <uves_cpl_size.h>
/*-----------------------------------------------------------------------------
                    Includes
 -----------------------------------------------------------------------------*/

#include <uves_utils_polynomial.h>
#include <uves_extract_iterate.h>
#include <uves_extract_profile.h>
#include <uves_chip.h>

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

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

/* If __func__ is not declared, use a default function name */
#if defined HAVE_DECL___FUNC__ && !HAVE_DECL___FUNC__
//static const char __func__[] = "<fctid>";
#ifndef __func__
#define __func__ "<fct.id>"
#endif
#endif

/*
 * The purpose of this target is to
 * decrease the amount of messages
 * printed at the debug level.
 *
 * If set to non-zero, even more messages
 * are printed at the debug level
 * (sometimes 50 - 100 MB)
 *
 */
#ifndef WANT_BIG_LOGFILE
#define WANT_BIG_LOGFILE 0
#endif

/*
 * Set to 1 to show timing
 * information on msg-level = info
 */
#ifndef WANT_TIME_MEASURE
#define WANT_TIME_MEASURE 0
#endif


#if WANT_TIME_MEASURE
#define UVES_TIME_START(what) uves_msg("Timing (%s, l%d) %s start", \
                       __FILE__, __LINE__, what)
#define UVES_TIME_END         uves_msg("Timing (%s, l%d) end", \
                       __FILE__, __LINE__)
#else
#define UVES_TIME_START(what) uves_msg_debug("Timing (%s, l%d) %s start", \
                         __FILE__, __LINE__, what)
#define UVES_TIME_END         uves_msg_debug("Timing (%s, l%d) end", \
                         __FILE__, __LINE__)
#endif


#ifndef stringify
#ifndef make_str
#define stringify(X) #X
#define make_str(X) stringify(X)
#endif
#endif

#define TWOSQRT2LN2 2.35482004503095

#ifndef M_PI 
#define M_PI 3.1415926535897932384626433832795
#endif

#define SPEED_OF_LIGHT  299792458    /* SI-units */

#define COS_DEG(x) cos(((x)/180)*M_PI)
#define SIN_DEG(x) sin(((x)/180)*M_PI)
#define ACOS_DEG(x) (acos(x)*180/M_PI)

/*-----------------------------------------------------------------------------
                                   Prototypes
 -----------------------------------------------------------------------------*/

cpl_image *
uves_create_image(uves_iterate_position *pos, enum uves_chip chip,
                  const cpl_image *spectrum, const cpl_image *sky,
                  const cpl_image *cosmic_image,
                  const uves_extract_profile *profile,
                  cpl_image **image_noise, uves_propertylist **image_header);
cpl_frameset *
uves_frameset_extract(const cpl_frameset *frames,const char *tag);

const char*
uves_string_tolower(char* s);
const char*
uves_string_toupper(char* s);

double uves_gaussrand(void);
double uves_pow_int(double x, int y);

/*----------------------------------------------------------------------------*/
/**
   @brief   Round a number to the nearest integer
   @param   x       The number to round
   @return  Nearest integer

   This is implemented as a function rather than a macro to avoid multiple
   evaluations of expressions that have side effects.
*/
/*----------------------------------------------------------------------------*/
static inline long
uves_round_double(double x)
{
    return (x >=0) ? (long)(x+0.5) : (long)(x-0.5);
}

/*----------------------------------------------------------------------------*/
/**
   @brief   Maximum of two numbers
   @param   x        First number
   @param   y        Second number
   @return  Maximum of @em x and @em y

   See also @c uves_round_double() .
*/
/*----------------------------------------------------------------------------*/
static inline double
uves_max_double(double x, double y)
{
    return (x >=y) ? x : y;
}
/*----------------------------------------------------------------------------*/
/**
   @brief   Maximum of two numbers
   @param   x        First number
   @param   y        Second number  
   @return  Maximum of @em x and @em y
  
   See also @c uves_round_double() .
*/
/*----------------------------------------------------------------------------*/
static inline int
uves_max_int(int x, int y)
{
    return (x >=y) ? x : y;
}

/*----------------------------------------------------------------------------*/
/**
   @brief   Minimum of two numbers
   @param   x        First number
   @param   y        Second number
   @return  Minimum of @em x and @em y
  
   See also @c uves_round_double() .
*/
/*----------------------------------------------------------------------------*/
static inline double
uves_min_double(double x, double y)
{
    return (x <=y) ? x : y;
}
/*----------------------------------------------------------------------------*/
/**
   @brief   Minimum of two numbers
   @param   x        First number
   @param   y        Second number
   @return  Minimum of @em x and @em y
  
   See also @c uves_round_double() .
*/
/*----------------------------------------------------------------------------*/
static inline int
uves_min_int(int x, int y)
{
    return (x <=y) ? x : y;
}

/*----------------------------------------------------------------------------*/
/**
   @brief   Get uncertainty of division
   @param  x  numerator
   @param  y  denominator
   @param  dx  uncertainty (one sigma) of @em x
   @param  dy  uncertainty (one sigma) of @em y
   @param  MIDAS  implement MIDAS formula
   @return  The uncertainty of (x/y)

*/
/*----------------------------------------------------------------------------*/
static inline double
uves_error_fraction(double x, double y, double dx, double dy)
{
    /* Error propagation:
     * sigma(x/y)^2 = (1/y sigma(x))^2 + (-x/y^2 sigma(y))^2 
     */
    return sqrt( dx*dx/(y*y) + x*x*dy*dy/(y*y*y*y) );
}

int uves_print_rec_status(const int val);
const char *uves_get_license(void);
cpl_error_code uves_get_version(int *major, int *minor, int *micro);
int uves_get_version_binary(void);

char * uves_initialize(cpl_frameset *frames, const cpl_parameterlist *parlist, 
               const char *recipe_id, const char *short_descr);
cpl_error_code uves_end(const char *recipe_id, const cpl_frameset *frames);
cpl_error_code
uves_table_add_extname(const char* fname,const char* xvalue,const int x_num);
uves_propertylist *uves_initialize_image_header(const char *ctype1, const char *ctype2, const char *cunit1, const char *cunit2, 
                           const char *bunit,const double bscale,
                           double crval1 , double crval2,
                           double crpix1 , double crpix2,
                           double crdelt1, double crdelt2);

cpl_parameterlist* 
uves_parameterlist_duplicate(const cpl_parameterlist* pin);

cpl_image *uves_define_noise(const cpl_image *image, const uves_propertylist *image_header,
                 int ncom, enum uves_chip);
cpl_image *uves_average_images(const cpl_image *image1, const cpl_image *noise1,
                   const cpl_image *image2, const cpl_image *noise2,
                   cpl_image **noise);


cpl_error_code uves_subtract_bias(cpl_image *image, const cpl_image *master_bias);
cpl_error_code uves_subtract_dark(cpl_image *image, const uves_propertylist *image_header,
                  const cpl_image *master_dark, 
                  const uves_propertylist *mdark_header);

polynomial *
uves_polynomial_regression_2d_autodegree(cpl_table *t,
                     const char *X1, const char *X2, const char *Y,
                     const char *sigmaY,
                     const char *polynomial_fit,
                     const char *residual_square, 
                     const char *variance_fit,
                     double *mean_squared_error, double *red_chisq,
                     polynomial **variance, double kappa,
                     int maxdeg1, int maxdeg2, double min_rms,
                                         double min_reject,
                                         bool verbose,
                     const double *min_val,
                     const double *max_val,
                     int npos, double positions[][2]);

polynomial *
uves_polynomial_regression_2d(cpl_table *t,
                  const char *X1, const char *X2, const char *Y, 
                  const char *sigmaY,
                  int degree1, int degree2,
                  const char *polynomial_fit, const char *residual_square, 
                  const char *variance_fit,
                  double *mse, double *red_chisq,
                  polynomial **variance, double kappa,
                              double min_reject);

polynomial *uves_polynomial_regression_1d(cpl_table *t, 
                      const char *X, const char *Y, const char *sigmaY, 
                      int degree, 
                      const char *polynomial_fit, const char *residual_square,
                      double *mean_squared_error, const double kappa);

const char *uves_remove_string_prefix(const char *s, const char *prefix);

double uves_spline_hermite_table( double xp, const cpl_table *t, const char *column_x, 
                  const char *column_y, int *istart );

double uves_spline_hermite( double xp, const double *x, const double *y, int n, int *istart );

double uves_spline_cubic(double xp, double *x, float *y, float *y2, int n, int *kstart );

int uves_absolute_order(int first_abs_order, int last_abs_order, int relative_order);

double uves_average_reject(cpl_table *t,
               const char *column,
               const char *residual2,
               double kappa);


cpl_table *uves_ordertable_traces_new(void);
cpl_error_code uves_ordertable_traces_add(cpl_table *traces, 
                      int fibre_ID, double fibre_offset, int fibre_mask);
bool uves_table_is_sorted_double(const cpl_table *t, const char *column, const bool reverse);

int uves_moffat(const double x[], const double a[], double *result);
int uves_moffat_derivative(const double x[], const double a[], double result[]);
int uves_gauss(const double x[], const double a[], double *result);
int uves_gauss_derivative(const double x[], const double a[], double result[]);
int uves_gauss_linear(const double x[], const double a[], double *result);
int uves_gauss_linear_derivative(const double x[], const double a[], double result[]);
void uves_check_version(void);
void uves_frameset_dump(cpl_frameset* set);
cpl_error_code
uves_rcosmic(cpl_image* ima,
             cpl_image** flt,
             cpl_image** out,
             cpl_image** msk,
             const double sky,
             const double ron,
             const double gain,
             const int ns,
             const double rc);

cpl_image *
uves_image_smooth_x(cpl_image * inp, const int r);
cpl_image *
uves_image_smooth_y(cpl_image * inp, const int r);

cpl_image *
uves_image_smooth_mean_x(cpl_image * inp, const int r);

cpl_image *
uves_image_smooth_median_x(cpl_image * inp, const int r);
cpl_image *
uves_image_smooth_fft(cpl_image * inp, const int fx);

cpl_image *
uves_ksigma_stack(const cpl_imagelist *imlist, double klow, double khigh, int kiter);


cpl_image *
uves_flat_create_normalized_master(cpl_imagelist * flats,
				   const cpl_table *ordertable,
                                   const polynomial* order_locations,
				   const cpl_vector* gain_vals,
				   double* fnoise);

cpl_image *
uves_flat_create_normalized_master2(cpl_imagelist * flats,
                                   const cpl_table *ordertable,
                                   const polynomial* order_locations,
                                    const cpl_image* mflat);

cpl_vector * 
uves_imagelist_get_clean_mean_levels(cpl_imagelist* iml, double kappa);
cpl_error_code
uves_imagelist_subtract_values(cpl_imagelist** iml, cpl_vector* values);
cpl_image *
uves_get_wave_map(cpl_image * ima_sci,
		  const char *context,
                  const cpl_parameterlist *parameters,
		  const cpl_table *ordertable,
		  const cpl_table *linetable,
		  const polynomial* order_locations,
		  const polynomial *dispersion_relation,
		  const int first_abs_order,
		  const int last_abs_order,
		  const int slit_size);

cpl_image*
uves_image_mflat_detect_blemishes(const cpl_image* flat, 
                                  const uves_propertylist* head);


cpl_error_code
uves_table_remove_units(cpl_table **table);
cpl_error_code
uves_table_unify_units(cpl_table **table2,  cpl_table **table1);
cpl_error_code
uves_tablenames_unify_units(const char* tname2, const char* tname1);
cpl_error_code
uves_tablename_remove_units(const char* tname);

#endif
