#include "gl_local.h"

NVPARSEPROC nvparse;
NVPARSEGETERRORSPROC nvparse_get_errors;

void SetupNVParse()
{
	HMODULE nvlib = LoadLibrary("nvparse.dll");
	nvparse=(NVPARSEPROC)GetProcAddress(nvlib,"nvparse");
	nvparse_get_errors=(NVPARSEGETERRORSPROC)GetProcAddress(nvlib,"nvparse_get_errors");
}

// glProgramStringARBPROC
unsigned int LoadVP(char *vp)
{
	char			*fbuf, *buf, path[128];
	unsigned int	size;
	char			**errors;

	unsigned int	vpid;

	sprintf(path,"shaders//%s",vp);
	size = ri.FS_LoadFile (path, (void **)&fbuf);

	if (!fbuf) 
	{
		ri.Con_Printf (PRINT_ALL, "Could not load shader %s\n", vp);
		return -1;
	}

	if (size < 16) 
	{
		ri.Con_Printf (PRINT_ALL, "Could not load shader %s\n", vp);
		ri.FS_FreeFile (fbuf);
		return -1;
	}

	buf = (char *)malloc(size+1);
	memcpy (buf, fbuf, size);
	buf[size] = 0;
	ri.FS_FreeFile (fbuf);

//void ProgramStringARB(enum target, enum format, sizei len, const void *string); 

	glGenProgramsARB(1,&vpid);
	glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vpid);
	glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, size, buf);

	{
//		char *err = qglGetString(GL_PROGRAM_ERROR_STRING_ARB);
//		ri.Con_Printf("Error:: %s\n",err);

//		return 0;
	}

	free(buf);
	return vpid;
}

unsigned int ParseShader(char *shader)
{
	char			*fbuf, *buf, path[128];
	unsigned int	size;
	char			**errors;

	unsigned int	dlist_id;
	unsigned int	errorcount = 0;

	sprintf(path,"shaders//%s",shader);
	size = ri.FS_LoadFile (path, (void **)&fbuf);

	if (!fbuf) 
	{
		ri.Con_Printf (PRINT_ALL, "Could not load shader %s\n", shader);
		return 0;
	}

	if (size < 16) 
	{
		ri.Con_Printf (PRINT_ALL, "Could not load shader %s\n", shader);
		ri.FS_FreeFile (fbuf);
		return 0;
	}

	buf = (char *)malloc(size+1);
	memcpy (buf, fbuf, size);
	buf[size] = 0;
	ri.FS_FreeFile (fbuf);

	dlist_id=qglGenLists(1);
	qglNewList(dlist_id, GL_COMPILE);
	nvparse(buf);
	qglEndList();
	free(buf);

	for (errors=(char **)nvparse_get_errors(); *errors; errors++) {
		ri.Con_Printf (PRINT_ALL, "#ERROR: %s\n", *errors);
		errorcount++;
	}
	if (errorcount) {
		qglDeleteLists(dlist_id,1);
		return 0;
	}
	return dlist_id;
}
