#include "main.h"
#include "system.h"
#include "quadexport.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define KB (1024)
#define MB (1024 * KB)
#define GB (1024 * MB)

static char* get_cmd_string(const char** cl)
{
	const char* start = (**cl == '\"') ? ((*cl)+1) : (*cl);
	const char* end = (**cl == '\"') ? strchr(start, '\"') : strchr(start, ' ');
	if(!end) end = strchr(start, 0);
	char* out = malloc(end - start + 1);
	if(out) {
		memcpy(out, start, end - start);
		out[end-start] = 0;
	}
	if(*end) end += 1;
	*cl = end;
	return out;
}

static void parse_cmd(const char* cmdline, int* start_vr, char** import_file, char** scene, size_t* vram_override, size_t* quadnum)
{
	//init params
	*start_vr = 0;
	*import_file = NULL;
	*scene = NULL;
	*vram_override = 0;
	*quadnum = 4096;

	//parse cmd
	const char* cl = cmdline;
	while(cl = strchr(cl, '-'))
	{
		cl += 1; if(!*cl) break;
		//full lenght parameters
		if(*cl == '-') {
			cl += 1; if(!*cl) break;
			//check param
			if(strncmp("vr", cl, 2) == 0) {*start_vr = 1; cl += 2;}
			else if(strncmp("import ", cl, 7) == 0) {
				cl += 7;
				*import_file = get_cmd_string(&cl);
			}
			else if(strncmp("scene ", cl, 6) == 0) {
				cl += 6;
				*scene = get_cmd_string(&cl);
			}
			else if(strncmp("vmem ", cl, 5) == 0) {
				cl += 5;
				*vram_override = 1024*1024*strtoull(cl,(char**)&cl,10);
			}
			else if(strncmp("boards ", cl, 7) == 0) {
				cl += 7;
				*quadnum = strtoull(cl,(char**)&cl,10);
			}
			//skip to next space
			else {
				const char* nxtcl = strchr(cl, ' ');
				if(!nxtcl) nxtcl = strchr(cl, 0);
				printf("Unknown option '%*s', ignored.", (int)(nxtcl - cl), cl);
				cl = nxtcl;
				if(!cl) break;
			}
		}
		//single char params
		else {
			while(*cl && *cl != ' ') {
				//check param
				switch(*cl) {
					case 'v': *start_vr = 1; break;
					case 'm': {
						cl += 1;
						*vram_override = 1024*1024*strtoull(cl,(char**)&cl,10);
						break;
					}
					 case 'b': {
						cl += 1;
						*quadnum = strtoull(cl,(char**)&cl,10);
						break;
					}
					break;
				}
				//goto next param
				cl += 1;
			}
		}
	}
}

int yr_appmain(void* appparam)
{
	const char* cmdline = appparam;
	int start_vr;
	char* import_file;
	char* scene;
	size_t vram_override;
	size_t quadnum;
	parse_cmd(cmdline, &start_vr, &import_file, &scene, &vram_override, &quadnum);

	int err = 0;
	if(import_file) {
		if(!scene) {
			printf("Please specify a scene file using '--scene [filename]'.");
			err = -1;
		} else {
			err = yrQuadImport_multi(scene, import_file);
			if(err) printf("An error occured while processing '%s'. Please check the log for more details.", import_file);
		}
	}
	else {
		//normal system init
		err = yrSystem_run(quadnum, vram_override, start_vr);
	}

	free(import_file);
	free(scene);
	return err;
}