/* @(#)interpolate.c	19.1 (ESO-IPG) 02/25/03 14:21:25 */
/*  
    
    Otmar Stahl

    interpolate.c
    
    spline interpolation of array 

*/

/* FEROS specific includes */

#include <mutil.h>
#include <nrutil.h>
#include <stdlib.h>

int interpolate
#ifdef __STDC__
(
 float in[], int howmany_in, float by_howmuch, float out[], int howmany_out
 )
#else
     (
      in, howmany_in, by_howmuch, out, howmany_out
      )
     float in[], out[], by_howmuch;
     int howmany_in, howmany_out;
#endif

{

  /* simple spline interpolation on equidistant grid */

  float diffx, sum, *xpos, x, startpos, stepsize;
  int i, in_entries, out_entries;
  double * p = malloc(howmany_in * sizeof(*p));
  int last = 0;

  diffx = -by_howmuch;
  in_entries = howmany_in;
  out_entries = howmany_out;
  stepsize = (float) out_entries / in_entries;

  startpos = 0.;
  while (startpos >= -0.5)
    startpos -= stepsize;
  startpos += stepsize;
  sum = 0.0;

  xpos = vector(1, in_entries);
 
  for (i = 1; i <= in_entries; i++)
    {
      xpos[i] = startpos + (((float) i) - 1.) * stepsize;
    }
  nat_spline(&xpos[1], in, in_entries, p);
  for (i = 0; i < out_entries; i++)
    {
      x = ((float) i)  + diffx;
      out[i] = nat_spline_int(&xpos[1], in, p, in_entries, x, &last);
    }
  for (i = 0; i < out_entries; i++)
    {
      sum += out[i];
    }
  for (i = 0; i < out_entries; i++)
    {
      out[i] /= sum;
    }
  free_vector(xpos, 1, in_entries); 
  free(p);
  return 0;
}
