/* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.

iem_dp written by IOhannes m zmoelnig, Thomas Musil, Copyright (c) IEM KUG Graz Austria 1999 - 2007 */
/* double precision library */


#include "m_pd.h"
#include "iemlib.h"
#include "iem_dp.h"

/* -------------------------- tabread4__ ------------------------------ */
/* based on miller's tabread4 which is part of pd */

static t_class *tabread4_dp_class;

typedef struct _tabread4_dp
{
  t_object  x_obj;
  t_symbol  *x_arrayname;
  t_float   x_residual;
} t_tabread4_dp;

static void *tabread4_dp_new(t_symbol *s)
{
  t_tabread4_dp *x = (t_tabread4_dp *)pd_new(tabread4_dp_class);

  x->x_arrayname = s;
  floatinlet_new(&x->x_obj, &x->x_residual);
  outlet_new(&x->x_obj, &s_float);
  return (x);
}

static void tabread4_dp_float(t_tabread4_dp *x, t_floatarg f)
{
  t_garray *ga;
  iemarray_t *vec;
  int npoints;

  if(!(ga = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class)))
  {
    if(*x->x_arrayname->s_name)
      pd_error(x, "tabread4__: %s: no such array", x->x_arrayname->s_name);
    iemarray_setfloat(vec, 0, 0.0f);
  }
  else if (!iemarray_getarray(ga, &npoints, &vec))
  {
    pd_error(x, "%s: bad template for tabread4__", x->x_arrayname->s_name);
    iemarray_setfloat(vec, 0, 0.0f);
  }
  else
  {
          double findex = iem_dp_calc_sum(f, x->x_residual);
    double frac;
    int index = findex;
    int maxindex = npoints - 3;
    t_sample a,  b,  c,  d, cmb;

    if(index < 1)
      index = 1, frac = 0;
    else if (index > maxindex)
      index = maxindex, frac = 1;
    else frac = findex - index;

    vec += index;

    a = iemarray_getfloat(vec,-1);
    b = iemarray_getfloat(vec, 0);
    c = iemarray_getfloat(vec, 1);
    d = iemarray_getfloat(vec, 2);

    cmb = c-b;
    outlet_float(x->x_obj.ob_outlet, (npoints ? b+frac*(cmb-0.1666667f*(1.-frac)*((d-a-3.0f*cmb)*frac+(d+2.0f*a-3.0f*b))) : 0));
  }
}

static void tabread4_dp_set(t_tabread4_dp *x, t_symbol *s)
{
    x->x_arrayname = s;
}

static void tabread4_dp_free(t_tabread4_dp *x)
{
}

void tabread4_dp_setup(void)
{
  tabread4_dp_class = class_new(gensym("tabread4__"),
    (t_newmethod)tabread4_dp_new, (t_method)tabread4_dp_free,
    sizeof(t_tabread4_dp), 0, A_DEFSYM, 0);
  class_addcreator((t_newmethod)tabread4_dp_new, gensym("tabread4''"), A_DEFSYM, 0);
  class_addfloat(tabread4_dp_class, (t_method)tabread4_dp_float);
  class_addmethod(tabread4_dp_class, (t_method)tabread4_dp_set, gensym("set"), A_SYMBOL, 0);
}
