/* Copyright (c) 1998 The Regents of the University of California.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.  */

/* sampling */

/* LATER make tabread4 and tabread~ */

#include "m_imp.h"

void garray_usedindsp(t_garray *x);

/* ------------------------- tabwrite~ -------------------------- */

static t_class *tabwrite_tilde_class;

typedef struct _tabwrite_tilde
{
    t_object x_obj;
    int x_phase;
    int x_nsampsintab;
    float *x_vec;
    t_symbol *x_arrayname;
    t_clock *x_clock;
} t_tabwrite_tilde;

static t_int *tabwrite_tilde_perform(t_int *w)
{
    t_tabwrite_tilde *x = (t_tabwrite_tilde *)(w[1]);
    t_float *in = (t_float *)(w[2]);
    int n = (int)(w[3]), phase = x->x_phase, endphase = x->x_nsampsintab;
    int nxfer = endphase - phase;
    if (!x->x_vec) goto bad;
    
    if (nxfer > n) nxfer = n;
    if (nxfer > 0)
    {
    	float *fp = x->x_vec + phase;
    	phase += nxfer;
    	while (nxfer--) *fp++ = *in++;
    	if (phase >= endphase)
    	{
    	    clock_delay(x->x_clock, 0);
    	    phase = 0x7fffffff;
    	}
    	x->x_phase = phase;
    }
bad:
    return (w+4);
}

static void tabwrite_tilde_dsp(t_tabwrite_tilde *x, t_signal **sp)
{
    t_garray *a;
    
    if (!(a = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class)))
    	error("%s: no such array", x->x_arrayname->s_name);
    else if (!garray_getfloatarray(a, &x->x_nsampsintab, &x->x_vec))
    	error("%s: bad template for tabwrite~", x->x_arrayname->s_name);
    else
    {
    	garray_usedindsp(a);
    	dsp_add(tabwrite_tilde_perform, 3, x, sp[0]->s_vec, sp[0]->s_n);
    }
}

static void tabwrite_tilde_bang(t_tabwrite_tilde *x)
{
    x->x_phase = 0;
}

static void tabwrite_tilde_tick(t_tabwrite_tilde *x)
{
    t_garray *a = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class);
    if (!a) bug("tabwrite_tilde_tick");
    else garray_redraw(a);
}

static void tabwrite_tilde_free(t_tabwrite_tilde *x)
{
    clock_free(x->x_clock);
}

static void *tabwrite_tilde_new(t_symbol *s)
{
    t_tabwrite_tilde *x = (t_tabwrite_tilde *)pd_new(tabwrite_tilde_class);
    x->x_phase = 0x7fffffff;
    x->x_nsampsintab = 0;
    x->x_arrayname = s;
    x->x_clock = clock_new(x, tabwrite_tilde_tick);
    return (x);
}

static void tabwrite_tilde_setup(void)
{
    tabwrite_tilde_class = class_new(gensym("tabwrite~"), tabwrite_tilde_new, tabwrite_tilde_free,
    	sizeof(t_tabwrite_tilde), 0, A_DEFSYM, 0);
    class_addmethod(tabwrite_tilde_class, nullfn, gensym("signal"), 0);
    class_addmethod(tabwrite_tilde_class, tabwrite_tilde_dsp, gensym("dsp"), 0);
    class_addbang(tabwrite_tilde_class, tabwrite_tilde_bang);
}

/******************** tabread4~ ***********************/

static t_class *tabread4_tilde_class;

typedef struct _tabread4
{
    t_object x_obj;
    int x_npoints;
    float *x_vec;
    t_symbol *x_arrayname;
} t_tabread4;

static t_int *tabread4_tilde_perform(t_int *w)
{
    t_tabread4 *x = (t_tabread4 *)(w[1]);
    t_float *in = (t_float *)(w[2]);
    t_float *out = (t_float *)(w[3]);
    int n = (int)(w[4]);    
    float maxindex;
    float *buf = x->x_vec, *fp;
    int i;
    
    maxindex = x->x_npoints - 3;    /* LATER deal with truncation error? */
    if (!buf) goto zero;

#if 0	    /* test for spam -- I'm not ready to deal with this */
    for (i = 0,  xmax = 0, xmin = maxindex,  fp = in1; i < n; i++,  fp++)
    {
	float f = *in1;
	if (f < xmin) xmin = f;
	else if (f > xmax) xmax = f;
    }
    if (xmax < xmin + x->c_maxextent) xmax = xmin + x->c_maxextent;
    for (i = 0, splitlo = xmin+ x->c_maxextent, splithi = xmax - x->c_maxextent,
	fp = in1; i < n; i++,  fp++)
    {
	float f = *in1;
	if (f > splitlo && f < splithi) goto zero;
    }
#endif

    for (i = 0; i < n; i++)
    {
	float findex = *in++;
	int index = findex;
	float frac,  a,  b,  c,  d, cminusb;
	static int count;
	if (index < 1) index = 1, frac = 0;
	else if (index > maxindex) index = maxindex, frac = 0;
	else frac = findex - index;
	fp = buf + index;
	a = fp[-1];
	b = fp[0];
	c = fp[1];
	d = fp[2];
	/* if (!i && !(count++ & 1023))
	    post("fp = %lx,  shit = %lx,  b = %f",  fp, buf->b_shit,  b); */
	cminusb = c-b;
	*out++ = b + frac * (
	    cminusb - 0.5f * (frac-1.) * (
		(a - d + 3.0f * cminusb) * frac + (b - a - cminusb)
	    )
	);
    }
    return (w+5);
 zero:
    while (n--) *out++ = 0;

    return (w+5);
}

static void tabread4_tilde_dsp(t_tabread4 *x, t_signal **sp)
{
    t_garray *a;
    
    if (!(a = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class)))
    	error("%s: no such array", x->x_arrayname->s_name);
    else if (!garray_getfloatarray(a, &x->x_npoints, &x->x_vec))
    	error("%s: bad template for tabread4~", x->x_arrayname->s_name);
    else
    {
    	garray_usedindsp(a);
    	dsp_add(tabread4_tilde_perform, 4, x,
    	    sp[0]->s_vec, sp[1]->s_vec, sp[0]->s_n);
    }
}

#if 0
static void tabread4_tilde_gensampname(char *buf, char *base, long int n)
{
    char b2[30];
    char *s = b2+29;
    *s = 0;
    if (n < 0) n = 0;
    while(*buf = *base++) buf++;
    if (!n) *(--s) = '0';
    else while (n)
    {
	*(--s) = '0' + (n%10);
	n /= 10;
    }
    while (*buf++ = *s++);
}

void tabread4_tilde_set(t_sigtabread4 *x, t_symbol *s)
{
    t_sigtable *wt;
    x->x_sym = s;
    if ((wt = (t_sigtable *)(s->s_thing)) &&
	ob_class(wt)->c_sym == tabread4_tilde_sigtablesym)
    {
	post("set to %s", s->s_name);
	x->x_ctl->c_buf = &wt->x_buf;
	if (wt->x_next)
	    post("tabread4(%s): warning: multiply defined", s->s_name);
    }
    else
    {
	error("tabread4: %s: no such sample", s->s_name);
	x->x_ctl->c_buf = 0;
    }
}

void tabread4_tilde_int(t_sigtabread4 *x, long int n)
{
    char buf[30];
    tabread4_tilde_gensampname(buf, "sample", n);
    tabread4_tilde_set(x, gensym(buf));
}
#endif

static void tabread4_tilde_free(t_tabread4 *x)
{
}

static void *tabread4_tilde_new(t_symbol *s)
{
    t_tabread4 *x = (t_tabread4 *)pd_new(tabread4_tilde_class);
    x->x_arrayname = s;
    outlet_new(&x->x_obj, gensym("signal"));
    return (x);
}

static void tabread4_tilde_setup(void)
{
    tabread4_tilde_class = class_new(gensym("tabread4~"), tabread4_tilde_new, tabread4_tilde_free,
    	sizeof(t_tabread4), 0, A_DEFSYM, 0);
    class_addmethod(tabread4_tilde_class, nullfn, gensym("signal"), 0);
    class_addmethod(tabread4_tilde_class, tabread4_tilde_dsp, gensym("dsp"), 0);
}

/* ------------------------ tabsend~ ------------------------- */

static t_class *tabsend_class;

typedef struct _tabsend
{
    t_object x_obj;
    float *x_vec;
    int x_graphperiod;
    int x_graphcount;
    t_symbol *x_arrayname;
    t_clock *x_clock;
} t_tabsend;

static t_int *tabsend_perform(t_int *w)
{
    t_tabsend *x = (t_tabsend *)(w[1]);
    t_float *in = (t_float *)(w[2]);
    int n = w[3];
    t_float *dest = x->x_vec;
    int i = x->x_graphcount;
    if (!x->x_vec) goto bad;

    while (n--) *dest++ = *in++;
    if (!i--)
    {
    	clock_delay(x->x_clock, 0);
    	i = x->x_graphperiod;
    }
    x->x_graphcount = i;
bad:
    return (w+4);
}

static void tabsend_dsp(t_tabsend *x, t_signal **sp)
{
    int i, vecsize;
    t_garray *a;

    if (!(a = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class)))
    	error("%s: no such array", x->x_arrayname->s_name);
    else if (!garray_getfloatarray(a, &vecsize, &x->x_vec))
    	error("%s: bad template for tabsend~", x->x_arrayname->s_name);
    else
    {
    	int n = sp[0]->s_n;
    	int ticksper = sp[0]->s_sr/n;
    	if (ticksper < 1) ticksper = 1;
    	x->x_graphperiod = ticksper;
    	if (x->x_graphcount > ticksper) x->x_graphcount = ticksper;
    	if (n < vecsize) vecsize = n;
    	garray_usedindsp(a);
    	dsp_add(tabsend_perform, 3, x, sp[0]->s_vec, vecsize);
    }
}

static void tabsend_tick(t_tabsend *x)
{
    t_garray *a = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class);
    if (!a) bug("tabsend_tick");
    else garray_redraw(a);
}

static void tabsend_free(t_tabsend *x)
{
    clock_free(x->x_clock);
}

static void *tabsend_new(t_symbol *s)
{
    t_tabsend *x = (t_tabsend *)pd_new(tabsend_class);
    x->x_graphcount = 0;
    x->x_arrayname = s;
    x->x_clock = clock_new(x, tabsend_tick);
    return (x);
}

static void tabsend_setup(void)
{
    tabsend_class = class_new(gensym("tabsend~"), tabsend_new, tabsend_free,
    	sizeof(t_tabsend), 0, A_DEFSYM, 0);
    class_addmethod(tabsend_class, nullfn, gensym("signal"), 0);
    class_addmethod(tabsend_class, tabsend_dsp, gensym("dsp"), 0);
}

/* ------------------------ tabreceive~ ------------------------- */

static t_class *tabreceive_class;

typedef struct _tabreceive
{
    t_object x_obj;
    float *x_vec;
    t_symbol *x_arrayname;
} t_tabreceive;

static t_int *tabreceive_perform(t_int *w)
{
    t_tabreceive *x = (t_tabreceive *)(w[1]);
    t_float *out = (t_float *)(w[2]);
    int n = w[3];
    t_float *from = x->x_vec;
    if (from) while (n--) *out++ = *from++;
    else while (n--) *out++ = 0;
    return (w+4);
}

static void tabreceive_dsp(t_tabreceive *x, t_signal **sp)
{
    t_garray *a;
    int vecsize;
    
    if (!(a = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class)))
    	error("%s: no such array", x->x_arrayname->s_name);
    else if (!garray_getfloatarray(a, &vecsize, &x->x_vec))
    	error("%s: bad template for tabreceive~", x->x_arrayname->s_name);
    else 
    {
    	int n = sp[0]->s_n;
    	if (n < vecsize) vecsize = n;
    	garray_usedindsp(a);
    	dsp_add(tabreceive_perform, 3, x, sp[0]->s_vec, vecsize);
    }
}

static void *tabreceive_new(t_symbol *s)
{
    t_tabreceive *x = (t_tabreceive *)pd_new(tabreceive_class);
    x->x_arrayname = s;
    outlet_new(&x->x_obj, &s_signal);
    return (x);
}

static void tabreceive_setup(void)
{
    tabreceive_class = class_new(gensym("tabreceive~"), tabreceive_new, 0,
    	sizeof(t_tabreceive), 0, A_DEFSYM, 0);
    class_addmethod(tabreceive_class, tabreceive_dsp, gensym("dsp"), 0);
}

/* ---------- tabread: control, non-interpolating ------------------------ */

static t_class *tabread_class;

typedef struct _tabread
{
    t_object x_obj;
    t_symbol *x_arrayname;
} t_tabread;

static void tabread_float(t_tabread *x, t_float f)
{
    t_garray *a;
    int npoints;
    t_float *vec;

    if (!(a = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class)))
    	error("%s: no such array", x->x_arrayname->s_name);
    else if (!garray_getfloatarray(a, &npoints, &vec))
    	error("%s: bad template for tabread", x->x_arrayname->s_name);
    else
    {
    	int n = f;
    	if (n < 0) n = 0;
    	else if (n >= npoints) n = npoints - 1;
    	outlet_float(x->x_obj.ob_outlet, (npoints ? vec[n] : 0));
    }
}

static void *tabread_new(t_symbol *s)
{
    t_tabread *x = (t_tabread *)pd_new(tabread_class);
    x->x_arrayname = s;
    outlet_new(&x->x_obj, &s_float);
    return (x);
}

static void tabread_setup(void)
{
    tabread_class = class_new(gensym("tabread"), tabread_new,
    	0, sizeof(t_tabread), 0, A_DEFSYM, 0);
    class_addfloat(tabread_class, (t_method)tabread_float);
}

/* ------------------ tabwrite: control ------------------------ */

static t_class *tabwrite_class;

typedef struct _tabwrite
{
    t_object x_obj;
    t_symbol *x_arrayname;
    t_clock *x_clock;
    float x_ft1;
    double x_updtime;
    int x_set;
} t_tabwrite;

static void tabwrite_tick(t_tabwrite *x)
{
    t_garray *a = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class);
    if (!a) bug("tabwrite_tick");
    else garray_redraw(a);
    x->x_set = 0;
    x->x_updtime = clock_getsystime();
}

static void tabwrite_float(t_tabwrite *x, t_float f)
{
    int i, vecsize;
    t_garray *a;
    t_float *vec;

    if (!(a = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class)))
    	error("%s: no such array", x->x_arrayname->s_name);
    else if (!garray_getfloatarray(a, &vecsize, &vec))
    	error("%s: bad template for tabwrite", x->x_arrayname->s_name);
    else
    {
    	int n = x->x_ft1;
    	double timesince = clock_gettimesince(x->x_updtime);
    	if (n < 0) n = 0;
    	else if (n >= vecsize) n = vecsize-1;
    	vec[n] = f;
    	if (timesince > 1000)
    	{
    	    tabwrite_tick(x);
    	}
    	else
    	{
    	    if (x->x_set == 0)
    	    {
    	    	clock_delay(x->x_clock, 1000 - timesince);
    	    	x->x_set = 1;
    	    }
    	}
    }
}

static void tabwrite_free(t_tabwrite *x)
{
    clock_free(x->x_clock);
}

static void *tabwrite_new(t_symbol *s)
{
    t_tabwrite *x = (t_tabwrite *)pd_new(tabwrite_class);
    x->x_ft1 = 0;
    x->x_arrayname = s;
    x->x_updtime = clock_getsystime();
    x->x_clock = clock_new(x, tabwrite_tick);
    floatinlet_new(&x->x_obj, &x->x_ft1);
    return (x);
}

void tabwrite_setup(void)
{
    tabwrite_class = class_new(gensym("tabwrite"), tabwrite_new, tabwrite_free,
    	sizeof(t_tabwrite), 0, A_DEFSYM, 0);
    class_addfloat(tabwrite_class, (t_method)tabwrite_float);
}

/* ------------------------ global setup routine ------------------------- */

void d_array_setup(void)
{
    tabwrite_tilde_setup();
    tabread4_tilde_setup();
    tabsend_setup();
    tabreceive_setup();
    tabread_setup();
    tabwrite_setup();
}

