#include <stdlib.h>
#include <plugins/lib_plot/plot_data.h>

#define BUFFLEN 1024

static int fill(plot_trace_t *tr, plot_trdata_t *trdata, plot_which_t which, long from, long len)
{
	double tmp[1024];
	long n;
	plot_pos_t pw;

	if (plot_write_init(&pw, tr, trdata, PLOT_MAIN, 0, 0, tmp, sizeof(tmp)/sizeof(tmp[0])) != 0)
		return -1;

	for(n = 0; n < len; n++)
		plot_write(&pw, n);

	plot_flush(&pw);
	return 0;
}


static void dump(plot_trace_t *tr, plot_trdata_t *td)
{
	double bmain[BUFFLEN], bmin[BUFFLEN], bmax[BUFFLEN], dmain, dmin, dmax;
	long n;
	plot_pos_t pmain, pmin, pmax;

	printf(" trace level %d of %ld pts\n", td->level, td->main.len);

	if (td->level == 0) {
		if (plot_read_init(&pmain, tr, td, PLOT_MAIN, 0, 0, bmain, sizeof(bmain)/sizeof(bmain[0])) != 0) {
			printf("  <error>\n");
			return;
		}
		while(plot_read(&pmain, &dmain) == 0)
			printf("  %.2f\n", dmain);
	}
	else {
		if (plot_read_init(&pmain, tr, td, PLOT_MAIN, 0, 0, bmain, sizeof(bmain)/sizeof(bmain[0])) != 0) {
			printf("  <error main>\n");
			return;
		}
		if (plot_read_init(&pmin, tr, td, PLOT_MIN, 0, 0, bmin, sizeof(bmin)/sizeof(bmin[0])) != 0) {
			printf("  <error min>\n");
			return;
		}
		if (plot_read_init(&pmax, tr, td, PLOT_MAX, 0, 0, bmax, sizeof(bmax)/sizeof(bmax[0])) != 0) {
			printf("  <error max>\n");
			return;
		}
		while((plot_read(&pmain, &dmain) == 0) && (plot_read(&pmin, &dmin) == 0) && (plot_read(&pmax, &dmax) == 0))
			printf("  %.2f [%.2f %.2f]\n", dmain, dmin, dmax);
	}
}

static void verify0(plot_trace_t *tr, plot_trdata_t *td)
{
	double bmain[BUFFLEN], dmain;
	long n;
	plot_pos_t pmain;

	if (plot_read_init(&pmain, tr, td, PLOT_MAIN, 0, 0, bmain, sizeof(bmain)/sizeof(bmain[0])) != 0)
		abort();

	n = 0;
	while(plot_read(&pmain, &dmain) == 0) {
		if (dmain != n)
			abort();
		n++;
	}
}

#define LEN 29

int main()
{
	plot_data_t *pt;
	FILE *fc = fopen("cache", "w+");
	plot_trace_t *tr;
	plot_trdata_t *td;

	pt = plot_data_alloc(1);
	tr = &pt->trace[0];
	plot_trace_init(tr, fc);

	td = plot_trdata_alloc(tr, 0, LEN);
	fill(tr, td, PLOT_MAIN, 0, LEN);

	td = plot_trdata_get(tr, 0, 1);
	dump(tr, td);
/*	verify0(tr, td);*/

	td = plot_trdata_get(tr, 1, 1);
	dump(tr, td);

	td = plot_trdata_get(tr, 2, 1);
	dump(tr, td);

	fclose(fc);
	plot_data_free(pt);
	return 0;
}
