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


/* ------------------------  max_dp  ---------------------------- */
/* based on miller's max, which is part of pd, only with double precision */

static t_class *max_dp_class;

typedef struct _max_dp
{
  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_max_dp;

static void max_dp_bang(t_max_dp *x)
{
  double dleft, dright;

  dleft = iem_dp_calc_sum(x->x_coarse_left, x->x_fine_left);
  dright = iem_dp_calc_sum(x->x_coarse_right, x->x_fine_right);
  if(dleft > dright)
  {
    outlet_float(x->x_out_fine, x->x_fine_left);
    outlet_float(x->x_out_coarse, x->x_coarse_left);
  }
  else
  {
    outlet_float(x->x_out_fine, x->x_fine_right);
    outlet_float(x->x_out_coarse, x->x_coarse_right);
  }
}

static void max_dp_float(t_max_dp *x, t_floatarg f)
{
  x->x_coarse_left = f;
  max_dp_bang(x);
}

static void *max_dp_new(t_symbol *s, int ac, t_atom *av)
{
  t_max_dp *x = (t_max_dp *)pd_new(max_dp_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);
}

void max_dp_setup(void)
{
  max_dp_class = class_new(gensym("max__"), (t_newmethod)max_dp_new, 0, sizeof(t_max_dp), 0, A_GIMME, 0);
  class_addcreator((t_newmethod)max_dp_new, gensym("max''"), A_GIMME, 0);
  class_addbang(max_dp_class, max_dp_bang);
  class_addfloat(max_dp_class, max_dp_float);
}
