/* 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"

/* -------------------------- tabread__ ------------------------------ */
/* based on miller's tabread which is part of pd */

static t_class *tabread_dp_class;

typedef struct _tabread_dp
{
  t_object  x_obj;
  t_symbol  *x_arrayname;
  t_float   x_residual;
} t_tabread_dp;

static void *tabread_dp_new(t_symbol *s)
{
  t_tabread_dp *x = (t_tabread_dp *)pd_new(tabread_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 tabread_dp_float(t_tabread_dp *x, t_floatarg f)
{
  t_garray *a;
  iemarray_t *vec;
  int npoints;

  if (!(a = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class)))
  {
    if (*x->x_arrayname->s_name)
      pd_error(x, "tabread__: %s: no such array", x->x_arrayname->s_name);
    vec = 0;
  }
  else if (!iemarray_getarray(a, &npoints, &vec))
  {
    pd_error(x, "%s: bad template for tabread__", x->x_arrayname->s_name);
    vec = 0;
  }
  else
  {
    double findex = iem_dp_calc_sum(f, x->x_residual);
    int n = findex;

    if(n < 0)
      n = 0;
    else if(n >= npoints)
      n = npoints - 1;
    outlet_float(x->x_obj.ob_outlet, (npoints ? iemarray_getfloat(vec, n) : 0));
  }
}

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

static void tabread_dp_free(t_tabread_dp *x)
{
}

void tabread_dp_setup(void)
{
  tabread_dp_class = class_new(gensym("tabread__"),
    (t_newmethod)tabread_dp_new, (t_method)tabread_dp_free,
    sizeof(t_tabread_dp), 0, A_DEFSYM, 0);
  class_addcreator((t_newmethod)tabread_dp_new, gensym("tabread''"), A_DEFSYM, 0);
  class_addfloat(tabread_dp_class, (t_method)tabread_dp_float);
  class_addmethod(tabread_dp_class, (t_method)tabread_dp_set, gensym("set"), A_SYMBOL, 0);
}
