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

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

static t_class *print_tilde_tilde_class;

typedef struct _print_tilde_tilde
{
  t_object  x_obj;
  t_float   x_f;
  t_symbol  *x_sym;
  int       x_count;
} t_print_tilde_tilde;

static void *print_tilde_tilde_new(t_symbol *s)
{
  t_print_tilde_tilde *x = (t_print_tilde_tilde *)pd_new(print_tilde_tilde_class);

  inlet_new(&x->x_obj, &x->x_obj.ob_pd, &s_signal, &s_signal);
  x->x_sym = (s->s_name[0] ? s : gensym("print~~"));
  x->x_count = 0;
  x->x_f = 0;
  return(x);
}

static t_int *print_tilde_tilde_perform(t_int *w)
{
  t_print_tilde_tilde *x = (t_print_tilde_tilde *)(w[1]);
  t_sample *inc = (t_sample *)(w[2]);
  t_sample *inf = (t_sample *)(w[3]);
  int n = (int)(w[4]);

  if(x->x_count)
  {
    post("%s:", x->x_sym->s_name);
    while(n >= 4)
    {
      post("%-20.14g %-20.14g %-20.14g %-20.14g", iem_dp_calc_sum(inc[0], inf[0]), iem_dp_calc_sum(inc[1], inf[1]),
              iem_dp_calc_sum(inc[2], inf[2]), iem_dp_calc_sum(inc[3], inf[3]));
      n -= 4;
      inc += 4;
      inf += 4;
    }
    if(n)
    {
      if(n == 3)
      {
        post("%-20.14g %-20.14g %-20.14g", iem_dp_calc_sum(inc[0], inf[0]), iem_dp_calc_sum(inc[1], inf[1]),
                    iem_dp_calc_sum(inc[2], inf[2]));
      }
      else if(n == 2)
      {
        post("%-20.14g %-20.14g", iem_dp_calc_sum(inc[0], inf[0]), iem_dp_calc_sum(inc[1], inf[1]));
      }
      else if(n == 1)
      {
        post("%-20.14g", iem_dp_calc_sum(inc[0], inf[0]));
      }
    }
    x->x_count--;
  }
  return(w+5);
}

static void print_tilde_tilde_float(t_print_tilde_tilde *x, t_floatarg f)
{
  if(f < 0)
    f = 0;
  x->x_count = f;
}

static void print_tilde_tilde_bang(t_print_tilde_tilde *x)
{
  x->x_count = 1;
}

static void print_tilde_tilde_dsp(t_print_tilde_tilde *x, t_signal **sp)
{
  dsp_add(print_tilde_tilde_perform, 4, x, sp[0]->s_vec, sp[1]->s_vec, sp[0]->s_n);
}

void print_tilde_tilde_setup(void)
{
  print_tilde_tilde_class = class_new(gensym("print~~"), (t_newmethod)print_tilde_tilde_new, 0,
    sizeof(t_print_tilde_tilde), 0, A_DEFSYM, 0);
  CLASS_MAINSIGNALIN(print_tilde_tilde_class, t_print_tilde_tilde, x_f);
  class_addmethod(print_tilde_tilde_class, (t_method)print_tilde_tilde_dsp, gensym("dsp"), A_CANT, 0);
  class_addbang(print_tilde_tilde_class, print_tilde_tilde_bang);
  class_addfloat(print_tilde_tilde_class, print_tilde_tilde_float);
}
