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

/* -------------------------- wrap~~ ------------------------------ */
/* based on miller's wrap~ which is part of pd */

static t_class *wrap_tilde_tilde_class;

typedef struct _wrap_tilde_tilde
{
  t_object  x_obj;
  t_float   x_f;
} t_wrap_tilde_tilde;

static void *wrap_tilde_tilde_new(void)
{
  t_wrap_tilde_tilde *x = (t_wrap_tilde_tilde *)pd_new(wrap_tilde_tilde_class);

  inlet_new(&x->x_obj, &x->x_obj.ob_pd, &s_signal, &s_signal);
  outlet_new(&x->x_obj, &s_signal);
  outlet_new(&x->x_obj, &s_signal);
  x->x_f = 0;
  return(x);
}

static t_int *wrap_tilde_tilde_perform(t_int *w)
{
  t_sample *inc = (t_sample *)(w[1]);
  t_sample *inf = (t_sample *)(w[2]);
  t_sample *outc = (t_sample *)(w[3]);
  t_sample *outf = (t_sample *)(w[4]);
  int n = (int)(w[5]);

  while(n--)
  {
    double coarse = *inc++;
    double fine = *inf++;
    double d=iem_dp_calc_sum(coarse, fine);
    int k=(int)d;
    t_float f;

    if(d > 0)
      d -= (double)k;
    else
      d -= (double)(k-1);

    f = iem_dp_cast_to_float(d);
    *outf++ = iem_dp_calc_residual(d, f);
          *outc++ = f;
  }
  return(w+6);
}

static void wrap_tilde_tilde_dsp(t_wrap_tilde_tilde *x, t_signal **sp)
{
  dsp_add(wrap_tilde_tilde_perform, 5, sp[0]->s_vec, sp[1]->s_vec, sp[2]->s_vec, sp[3]->s_vec, sp[0]->s_n);
}

void wrap_tilde_tilde_setup(void)
{
  wrap_tilde_tilde_class = class_new(gensym("wrap~~"), (t_newmethod)wrap_tilde_tilde_new, 0,
    sizeof(t_wrap_tilde_tilde), 0, 0);
  CLASS_MAINSIGNALIN(wrap_tilde_tilde_class, t_wrap_tilde_tilde, x_f);
  class_addmethod(wrap_tilde_tilde_class, (t_method)wrap_tilde_tilde_dsp, gensym("dsp"), A_CANT, 0);
}
