/* qelem3~.c  Correct solution
** actually it uses clock_delay() with delay of 0
** the clock will execute at every I/O vector interrupt
** this behaves similar to spike~ at least until I/O vector Size of 64
** It also means that spike~ cannot output faster than I/O vector size interrupts
** even if the spikes occur faster more often
** 02/11/12 IF
** 04/10/26 IF Xcode
** 05/10/30 IF cleanup
*/

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

#define MAXCOUNT 1000

void *qtest_class;

typedef struct _qtest 	// Data structure for this object
{
    t_pxobject t_obj;
    void *out;			// right int outlet
    int count;
    void *qe;
    void *t_clock;
} t_qtest;

void *qtest_new(void);
t_int *qtest_perform(t_int *w);
void qtest_dsp(t_qtest *x, t_signal **sp, short *count);
void qtest_free(t_qtest *x);
void out_count(t_qtest *x);

int main(void)
{
    setup((t_messlist **)&qtest_class, (method)qtest_new, (method)qtest_free, (short)sizeof(t_qtest), 0L, 0);
    addmess((method)qtest_dsp, "dsp", A_CANT, 0);
    dsp_initclass();	
	return(0);
}

void *qtest_new(void)
{
	t_qtest *x = (t_qtest *)newobject(qtest_class);
	dsp_setup((t_pxobject*)x, 0);			// no signal inlet
	x->out = intout((t_qtest *)x);
	x->count = 0;
	x->t_clock = clock_new(x, (method)out_count);

	return (x);
}

void qtest_free(t_qtest *x)
{
	clock_free(x->t_clock);
	dsp_free((t_pxobject*)x);
}

void out_count(t_qtest *x)
{
	outlet_int(x->out, x->count);
}

void qtest_dsp(t_qtest *x, t_signal **sp, short *count)
{
	dsp_add(qtest_perform, 1,  x);
}

t_int *qtest_perform(t_int *w) // count is incremented at every Signal Vector interrupt
{
	t_qtest *x = (t_qtest *)w[3];
	
	if (x->count++ > MAXCOUNT)
		x->count = 0;
	clock_delay(x->t_clock, 0);

    return (w + 2); // always add one more than the 2nd argument in dsp_add()
}


