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


/* ------------------------  div__ or /__  ---------------------------- */
/* based on miller's /, which is part of pd, only with double precision */

static t_class *div___class;

typedef struct _div__
{
  t_object  x_obj;
  t_float   x_coarse_left;
  t_float   x_fine_left;
  t_float   x_coarse_right;
  t_float   x_fine_right;
  t_outlet  *x_out_coarse;
  t_outlet  *x_out_fine;
} t_div__;

static void div___bang(t_div__ *x)
{
  double ddiv, nom;
  t_float fdiv;

  nom = iem_dp_calc_sum(x->x_coarse_right, x->x_fine_right);
  ddiv = (nom ? iem_dp_calc_sum(x->x_coarse_left, x->x_fine_left) / nom : 0);
  fdiv = (t_float)ddiv;
  outlet_float(x->x_out_fine, iem_dp_calc_residual(ddiv, fdiv));
  outlet_float(x->x_out_coarse, fdiv);
}

static void div___float(t_div__ *x, t_floatarg f)
{
  x->x_coarse_left = f;
  div___bang(x);
}

static void *div___new(t_symbol *s, int ac, t_atom *av)
{
  t_div__ *x = (t_div__ *)pd_new(div___class);

  floatinlet_new(&x->x_obj, &x->x_fine_left);
  floatinlet_new(&x->x_obj, &x->x_coarse_right);
  floatinlet_new(&x->x_obj, &x->x_fine_right);
  x->x_coarse_left = 0.0f;
  x->x_fine_left = 0.0f;
  if((ac > 0) && (IS_A_FLOAT(av, 0)))
    x->x_coarse_right = atom_getfloatarg(0, ac, av);
  else
    x->x_coarse_right = 0.0f;
  if((ac > 1) && (IS_A_FLOAT(av, 1)))
    x->x_fine_right = atom_getfloatarg(1, ac, av);
  else
    x->x_fine_right = 0.0f;
  x->x_out_coarse = outlet_new(&x->x_obj, &s_float);
  x->x_out_fine = outlet_new(&x->x_obj, &s_float);
  return (x);
}

static void div___free(t_div__ *x)
{
}

void div___setup(void)
{
  div___class = class_new(gensym("div__"), (t_newmethod)div___new, 0, sizeof(t_div__), 0, A_GIMME, 0);
  class_addcreator((t_newmethod)div___new, gensym("/__"), A_GIMME, 0);
  class_addcreator((t_newmethod)div___new, gensym("/''"), A_GIMME, 0);
  class_addbang(div___class, div___bang);
  class_addfloat(div___class, div___float);
}
