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

/* -------------------------- tabwrite__ ------------------------------ */
/* based on miller's tabwrite which is part of pd */

static t_class *tabwrite_dp_class;

typedef struct _tabwrite_dp
{
  t_object  x_obj;
  t_symbol  *x_arrayname;
  t_float   x_float_casted_index;
  t_float   x_residual_index;
} t_tabwrite_dp;

static void *tabwrite_dp_new(t_symbol *s)
{
  t_tabwrite_dp *x = (t_tabwrite_dp *)pd_new(tabwrite_dp_class);

  x->x_arrayname = s;
  x->x_float_casted_index = 0.0f;
  x->x_residual_index = 0.0f;
  floatinlet_new(&x->x_obj, &x->x_float_casted_index);
  floatinlet_new(&x->x_obj, &x->x_residual_index);
  return (x);
}

static void tabwrite_dp_float(t_tabwrite_dp *x, t_floatarg fvalue)
{
  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, "tabwrite__: %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 tabwrite__", x->x_arrayname->s_name);
    vec = 0;
  }
  else
  {
          double findex = iem_dp_calc_sum(x->x_float_casted_index, x->x_residual_index);
    int n = findex;

    if(n < 0)
      n = 0;
    else if(n >= npoints)
      n = npoints - 1;
    if(npoints)
    {
      iemarray_setfloat(vec, n, fvalue);
      garray_redraw(a);
    }
  }
}

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

void tabwrite_dp_setup(void)
{
  tabwrite_dp_class = class_new(gensym("tabwrite__"),
    (t_newmethod)tabwrite_dp_new, 0,
    sizeof(t_tabwrite_dp), 0, A_DEFSYM, 0);
  class_addcreator((t_newmethod)tabwrite_dp_new, gensym("tabwrite''"), A_DEFSYM, 0);
  class_addfloat(tabwrite_dp_class, (t_method)tabwrite_dp_float);
  class_addmethod(tabwrite_dp_class, (t_method)tabwrite_dp_set, gensym("set"), A_SYMBOL, 0);
}
