#include <v_lib.h>
#include "framebuf.h"
#include "cspace.h"
#include "eval.h"

void usage(char *name)
{
	puts("Image processing language interpreter.\n"
		"Version 0.49 by Vladimir A. Smirnov.");
	printf("Usage: %s <scriptfile>\n",name);
	printf("For language description, type %s --help-ipl.\n",name);
}

u32_t random_seed = 1;

vhandle_t random_gen = LIBV_INVALID_HANDLE;

void
evalGlobals(vhandle_t script)
{
	if(tokSkipToEx(script,"random_seed",STR_COMP))
	{
		if(!tokNextInteger(script,(s32_p)&random_seed))
		{
			conlPuts(LOG_WARNING,"evalGlobals(): error "
				"getting random_seed, using default value '1'.\n");
			random_seed = 1;
		}
	}
	tokRestart(script);
}

int main(int argc,char *argv[])
{
	vhandle_t script;
	vboolean result;
	u32_t nbytes, nblocks, nhandles;
	u32_t nbytes_out, nblocks_out, nhandles_out;
	logStartConsoleLog();
	logUpperLevel(LOG_TRACE);
	if(argc != 2)
	{
		usage(argv[0]);
		return -1;
	}
	if(STR_EQ(argv[1],"--help"))
	{
		usage(argv[0]);
		return 0;
	}
	if(STR_EQ(argv[1],"--help-ipl"))
	{
		evalHelp();
		return 0;
	}
	if(STR_EQ(argv[1],"--help-state"))
	{
		stateHelp();
		return 0;
	}
	script = tokParseFile(argv[1],"{}");
	if(script == LIBV_INVALID_HANDLE)
	{
		conlPrintf(LOG_ERROR,"main(): unable to parse '%s'\n",argv[1]);
		return -1;
	}
	tokCommentChar(script,'#');
	evalGlobals(script);
	random_gen = urnCreateGenerator(random_seed);
	V_ASSERT(random_gen);
	result = evalAll(script);
	memStats(&nbytes,&nblocks,&nhandles);
	urnDestroyGenerator(random_gen);
	inputCollectGarbage();
	evalFreeAllArgs();
	evalFreeAllOperands();
	evalDestroyAllFourierTransformers();
	tokDestroy(script);
	logStopConsoleLog();
	memStats(&nbytes_out,&nblocks_out,&nhandles_out);
	printf("IPL run completed: %s. "
		"(alloc: %u bytes, %u blocks, %u handles; leak: %u bytes)\n",
		result ? "success" : "error(s)",nbytes,nblocks,nhandles,nbytes_out);
	return 0;
}
