/* defer~.c  defer_low: first attempt.  Doesn't work
** 
** 02/11/11 IF
** 04/10/26 IF Xcode
*/

#include "ext.h"    // Required for all Max external objects
#include "z_dsp.h"  // Required for all MSP external objects

void *defer_class;

typedef struct _defer 	// Data structure for this object
{
    t_pxobject t_obj;
    void *out;
    int count;
} t_defer;

void *defer_new(void);
t_int *defer_perform(t_int *w);
void defer_dsp(t_defer *x, t_signal **sp, short *count);
void out_int(t_defer *x, t_symbol *s, short argc, t_atom *argv);

int main(void)
{
    setup((t_messlist **)&defer_class, (method)defer_new, (method)dsp_free, (short)sizeof(t_defer), 0L, 0);
    addmess((method)defer_dsp, "dsp", A_CANT, 0);
    dsp_initclass();
	return(0);
}

void *defer_new(void)
{
	t_defer *x = (t_defer *)newobject(defer_class);
	dsp_setup((t_pxobject*)x, 0);			// no signal inlet
	x->out = intout((t_defer *)x);
	outlet_new((t_defer *)x, "signal");	// left signal outlet, must come after floatout
	x->count = 0;
	return (x);
}

void out_int(t_defer *x, t_symbol *s, short argc, t_atom *argv)
{
	outlet_int(x->out, x->count);
}

void defer_dsp(t_defer *x, t_signal **sp, short *count)
{
	dsp_add(defer_perform, 3, sp[0]->s_vec, sp[0]->s_n, x);
}

t_int *defer_perform(t_int *w)
{
    t_float *out = (t_float *)(w[1]);
	int n = (int)(w[2]);
	t_defer *x = (t_defer *)w[3];
	
	while (n--) 
		*out++ = 0; 
	if (x->count++ > 1000)
		x->count = 0;
	defer_low((t_defer *)x, (method)out_int, NIL, 0, NIL);
    return (w + 4); // always add one more than the 2nd argument in dsp_add()
}


