/* qelem3~.c  Correct solution
** actually it uses clock_delay() with delay of 0
** this is the correct answer for spike~
** 02/11/12 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 *qtest_class;

typedef struct _qtest 	// Data structure for this object
{
    t_pxobject t_obj;
    void *out;
    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, 1);			// signal inlet
	x->out = intout((t_qtest *)x);
	outlet_new((t_qtest *)x, "signal");	// left signal outlet, must come after floatout
	x->count = 0;
//	x->qe = qelem_new(x, (method)out_count);
	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, 4, sp[0]->s_vec, sp[1]->s_vec, sp[0]->s_n, x);
}

t_int *qtest_perform(t_int *w)
{
    t_float *in = (t_float *)(w[1]);
    t_float *out = (t_float *)(w[2]);
	int n = (int)(w[3]);
	t_qtest *x = (t_qtest *)w[4];
	
//	while (n--) 
//		*out++ = *in++;
	if (x->count++ > 1000)
		x->count = 0;
//	qelem_front(x->qe);
	clock_delay(x->t_clock, 0);

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


