#include <v_lib.h>

#define		NUM_SUBDIVISIONS		4096

vec2_t	xy[]={{0,0},{10,10},{20,0},{30,-10},{40,0},{50,10}};

int main()
{
	u32_t i;
	vector_t *x,*y,*smoothed;
	vhandle_t sp;
	vhandle_t t;
	vec_t mult;
	input_record_t in_rec;
	
	logStartConsoleLog();
	logUpperLevel(LOG_TRACE);
	
	/* create input data */
	x=vecAlloc(6);
	y=vecAlloc(x->size);
	smoothed=vecAlloc(NUM_SUBDIVISIONS);
	
	for(i=0;i<x->size;i++)
	{
		/*
		x->elements[i]=(vec_t)i;
		y->elements[i]=(9.0f * (rand() % 1024)) / 1024;
		*/
		x->elements[i]=xy[i][0];
		y->elements[i]=xy[i][1];
	}
	sp=cspCreate(x,y);
	cspSetBoundaryCondition(sp,false,0,0);

	/* initialize OpenGL */
	vglCreateWindow("Spline test (press ESC to exit)",
		0,0,640,480);
	glClearColor(0,0.3f,0.3f,0.5f);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-10,60,-12,12,-1,1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glClear(GL_COLOR_BUFFER_BIT);
	
	/* draw input data */
	glColor4f(1,1,1,0.7f);
	glPointSize(9);
	glEnable(GL_POINT_SMOOTH);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glBegin(GL_POINTS);
		for(i=0;i<x->size;i++)
			glVertex2d(x->elements[i],y->elements[i]);
	glEnd(); /* GL_POINTS */
	glDisable(GL_POINT_SMOOTH);
	glDisable(GL_BLEND);

	/* compute curve and smooth input data */
	mult=50.0f / smoothed->size;
	t=timerCreate();
	timerStart(t);
	for(i=0;i<smoothed->size;i++)
		smoothed->elements[i]=cspInterpolate(sp,(vec_t)i * mult);
	printf("%d points, %d milliseconds.\n",smoothed->size,timerMilliseconds(t));
	timerStop(t);
	timerDestroy(t);
	
	/* draw smoothed data */
	glColor4f(1,1,0,1);
	glBegin(GL_LINE_STRIP);
		for(i=0;i<smoothed->size;i++)
			glVertex2d((vec_t)i * mult,smoothed->elements[i]);
	glEnd(); /* GL_LINE_STRIP */
	vglSwapBuffers();

	for(;;)
	{
		vglNextEvent(&in_rec);
		if(in_rec.first_code==key_escape)
			break;
	}

	vglDestroyWindow(vglGetCurrentWindow());
	memFree(x);
	memFree(y);
	memFree(smoothed);
	cspDestroy(sp);
	
	memPrintStats();
	
	return 0;
}
