#include <time.h>
#include <v_lib.h>
#include "config.h"
#include "goal.h"

char outdir[_MAX_PATH];

void usage(char *me)
{
	conPrintf("Usage: %s <scriptfile>, where scriptfile is an PSDL script.\n",me);
	conPuts("For brief description of PSDL, try --help-psdl.");
	conPuts("For brief description of available controllers, try --help-controllers.");
}

int main(int argc, char *argv[])
{
	int i;
	char *fname = NULL;
	char logname[_MAX_PATH];
	time_t t;
	struct tm *tm;
	vboolean retval;
	logStartConsoleLog();
	t = time(NULL);
	tm = localtime(&t);
	strftime(outdir,_MAX_PATH,"out-%Y-%m-%d-%Hh-%Mm-%Ss",tm);
	sprintf(logname,"%s/psmod.log",outdir);
	logStartFileLog(logname, true);
	logUpperLevel(LOG_LEVEL);
	conPrintf("%s\n", PSMOD_DESCRIPTION);
	if(argc == 1)
	{
		help_main(argv[0]);
		return -1;
	}
	for(i = 1;i < argc;i++)
	{
		if(argv[i][0] == '-' && argv[i][1] == '-')
		{
			if(!strcasecmp(argv[i],"--help"))
			{
				help_main(argv[0]);
				return 0;
			}
			if(!strcasecmp(argv[i],"--help-psdl"))
			{
				help_PSDL();
				return 0;
			}
			if(!strcasecmp(argv[i],"--help-controllers"))
			{
				help_controllers();
				return 0;
			}
			conlPrintf(LOG_WARNING,"main(): unknown option \"%s\"\n", argv[i]);
		}
		else
		{
			if(fname)
				conlPrintf(LOG_WARNING,"main(): extra file name given: \"%s\", ignoring \"%s\".\n",
					argv[i], fname);
			fname = argv[i];
		}
	}
	if(!fname)
	{
		conlPrintf(LOG_ERROR,"main(): no file name given.\n");
		return -1;
	}
	retval = goalsRun(fname);
	util_shutdown();
	goalsDestroy();
	clearControllersCache();
	util_shutdown();
	memPrintStats();
	memPrintMemStats();
	memPrintObjStats();
	return retval ? 0 : 1;
}
