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


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

static t_class *phasor_tilde_tilde_class, *scalarphasor_tilde_tilde_class;

typedef struct _phasor_tilde_tilde
{
  t_object  x_obj;
  double    x_phase;
  double    x_rcp_sr;
  t_float   x_freq;
} t_phasor_tilde_tilde;

static void *phasor_tilde_tilde_new(t_floatarg freq)
{
  t_phasor_tilde_tilde *x = (t_phasor_tilde_tilde *)pd_new(phasor_tilde_tilde_class);

  inlet_new(&x->x_obj, &x->x_obj.ob_pd, &s_float, gensym("ft1"));
  x->x_phase = 0;
  x->x_rcp_sr = 0;
  outlet_new(&x->x_obj, &s_signal);
  outlet_new(&x->x_obj, &s_signal);
  x->x_freq = freq;
  return(x);
}

static t_int *phasor_tilde_tilde_perform(t_int *w)
{
  t_phasor_tilde_tilde *x = (t_phasor_tilde_tilde *)(w[1]);
  t_sample *freq_in = (t_sample *)(w[2]);
  t_sample *outc = (t_sample *)(w[3]);
  t_sample *outf = (t_sample *)(w[4]);
  int n = (int)(w[5]);
  double dphase = x->x_phase;
  double rcp_sr = x->x_rcp_sr;
  double fin;
  t_float fphase;
  int k;

  while(n--)
  {
    fin = (double)*freq_in++;

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

    fphase = iem_dp_cast_to_float(dphase);
    *outf++ = iem_dp_calc_residual(dphase, fphase);
    *outc++ = fphase;

    dphase += fin * rcp_sr;
  }
  x->x_phase = dphase;
  return(w+6);
}

static void phasor_tilde_tilde_dsp(t_phasor_tilde_tilde *x, t_signal **sp)
{
  x->x_rcp_sr = (double)(1.0)/(double)(sp[0]->s_sr);
  dsp_add(phasor_tilde_tilde_perform, 5, x, sp[0]->s_vec, sp[1]->s_vec, sp[2]->s_vec, sp[0]->s_n);
}

static void phasor_tilde_tilde_ft1(t_phasor_tilde_tilde *x, t_floatarg ph)
{
  x->x_phase = (double)ph;
}

void phasor_tilde_tilde_setup(void)
{
  phasor_tilde_tilde_class = class_new(gensym("phasor~~"), (t_newmethod)phasor_tilde_tilde_new, 0,
    sizeof(t_phasor_tilde_tilde), 0, A_DEFFLOAT, 0);
  CLASS_MAINSIGNALIN(phasor_tilde_tilde_class, t_phasor_tilde_tilde, x_freq);
  class_addmethod(phasor_tilde_tilde_class, (t_method)phasor_tilde_tilde_dsp, gensym("dsp"), A_CANT, 0);
  class_addmethod(phasor_tilde_tilde_class, (t_method)phasor_tilde_tilde_ft1, gensym("ft1"), A_FLOAT, 0);
}
