/*                                                                            *
 *   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-07-21 08:32:42 $
 * $Revision: 1.1 $
 * $Name: not supported by cvs2svn $
 */
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

/*--------------------------------------------------------------------------*/
/**
 * @defgroup test_xsh_tests_create_map Test Create SLITMAP and WAVEMAP
 * @ingroup unit_tests
 *
 */
/*--------------------------------------------------------------------------*/
/**@{*/

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


#include <xsh_error.h>
#include <xsh_msg.h>
#include <xsh_dfs.h>
#include <tests.h>
#include <cpl.h>
#include <math.h>
#include <getopt.h>
#include <string.h>
/*---------------------------------------------------------------------------
                            Defines
 ---------------------------------------------------------------------------*/
#define MODULE_ID "XSH_CPL_VECTOR_CORREL_GAUSSIANS"

enum {
  DEBUG_OPT, HELP_OPT
};

static struct option LongOptions[] = {
  {"debug", required_argument, 0, DEBUG_OPT},
  {"help", 0, 0, HELP_OPT},
  {NULL, 0, 0, 0}
};

static void Help( void )
{
  puts ("Unitary test : Create two Gaussians one shifted to the other of a given quantity, then correlate them to check if correlation returns expected shift");
  puts( "Usage : ./tetst_xsh_correl_gaussians [options]");

  puts( "Options" ) ;
  puts( " --debug=<n>        : Level of debug LOW | MEDIUM | HIGH [MEDIUM]" );
  puts( " --help             : What you see" ) ;

  puts( "The input files argument MUST be in this order:" );
  puts( " 1. PRE frame");
  puts( " 2. SOF a) MODEL     : [XSH_MOD_CFG_TAB_UVB]");
  puts( "        b) POLYNOMIAL: [DISP_TAB, ORDER_TAB_EDGES]");
  
  TESTS_CLEAN_WORKSPACE(MODULE_ID);
  TEST_END();
  exit(0);
}

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

  while( (opt = getopt_long( argc, argv, "debug:help",
                             LongOptions, &option_index )) != EOF){
    switch( opt ) {
    case DEBUG_OPT:
      if ( strcmp( optarg, "LOW")==0){
        xsh_debug_level_set( XSH_DEBUG_LEVEL_LOW);
      }
      else if ( strcmp( optarg, "HIGH")==0){
        xsh_debug_level_set( XSH_DEBUG_LEVEL_HIGH);
      }
      break;
    case HELP_OPT:
      Help();
      break;
    default:
      break;
    }
  }
}

cpl_error_code
xsh_gauss_gen(double* data,const double center,const double sigma, const int size)
{

  int i=0;
  double x=0;
  double inv_2_c2=0.5/sigma/sigma;
  double norm=sigma*sqrt(2*CPL_MATH_PI);
  double a=1./norm;

  for(i=0;i<size;i++) {
    x=i;
    data[i]=a*exp(-(x-center)*(x-center)*inv_2_c2);
  }

  return cpl_error_get_code();
}

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

/*--------------------------------------------------------------------------*/
/**
  @brief    Create a SLITMAP and a WAVEMAP from Set Of Files (SOF)
  @return   0 if success

  Test the Data Reduction Library function XSH_CREATE_MAP
 */
/*--------------------------------------------------------------------------*/

int main( int argc, char** argv)
{
  /* Initialize libraries */
  TESTS_INIT_WORKSPACE(MODULE_ID);
  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) >= 2) {
    Help();
  }

  int ret=0;
  int size=100;
  double shift_i=5.15;
  //double shift_o=0;
  double gauss_c=0.5*size;
  double gauss_s=10.;
  double* gauss_d1=NULL;
  double* gauss_d2=NULL;


  cpl_vector* gauss_v1=cpl_vector_new(size);
  cpl_vector* gauss_v2=cpl_vector_new(size);

  gauss_d1=cpl_vector_get_data(gauss_v1);
  gauss_d2=cpl_vector_get_data(gauss_v2);

  check(xsh_gauss_gen(gauss_d1,gauss_c,gauss_s,size));
  check(xsh_gauss_gen(gauss_d2,gauss_c+shift_i,gauss_s,size));


  //int half_search=(int)(2*gauss_s+1);
  int len_corr=2*size-1;


  /* CPL VECTOR */

  cpl_vector* correl=cpl_vector_new(len_corr);
  check(cpl_vector_fill(correl, 0.0));
  double shift=cpl_vector_correlate(correl,gauss_v1,gauss_v2);

  cpl_vector_save(correl,"correl.fits",CPL_BPP_IEEE_FLOAT,NULL,CPL_IO_DEFAULT);
  xsh_msg("shift=%g",shift);
  //cpl_vector_dump(correl,stdout);
  double max=0;
  int maxpos=0;
  double* pvec=NULL;
  /* get maxpos */
  pvec=cpl_vector_get_data(correl);
  max=-100;
  int i=0;
  for(i=1;i<len_corr;i++) {
    if(max<pvec[i] ) {
      max=pvec[i];
      maxpos=i;
    }
  }
  xsh_msg("maxpos my determination: %d",maxpos);

  double a=0;
  double b=0;
  double c=0;
  double fraction=0;
  //maxpos +=1;
  a=cpl_vector_get(correl,maxpos-1);
  b=cpl_vector_get(correl,maxpos+1);
  c=cpl_vector_get(correl,maxpos);
  fraction=(a-b)/(2.*a+2.*b-4.*c);
  xsh_msg("len_corr=%d",len_corr);
  xsh_msg("a=%g b=%g c=%g fraction=%g",a,b,c,fraction);
  xsh_msg("shift - (size-1)=%g",shift -(size-1));
  xsh_msg("fraction shift - (size-1)=%g",shift -(size-1)+fraction);

  
 cleanup: 
  xsh_free_vector(&gauss_v1);
  xsh_free_vector(&gauss_v2);
  xsh_free_vector(&correl);


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

/**@}*/
