#include "lib2.h"

/*-->|  only interpreter

void *stdout_write = eval("sys.stdout.write");
void *stdout_flush = eval("sys.stdout.flush");

void *sys_int = eval("int");

void atoi(char *s)
{
	return sys_int(s);
}

sys_exec("global math ; import math");
double M_PI = eval("math.pi");
void *sin = eval("math.sin");

sys_exec("global time ; import time");
void *sys_sec = eval("time.time");
void *sys_sleep = eval("time.sleep");

void *NULL = 0;

int strcmp(char *a, char *b)
{
	return (a == b) ? 0 : (a < b) ? -1 : 1;
}

|<--*/  // only interpreter

//|-->  only compiler

void stdout_write(char *s)
{
	printf("%s", s);
}

void stdout_flush(void)
{
	fflush(stdout);
}

//<--|  // only compiler

void show_str(char *s)
{
	stdout_write(s);
	stdout_flush();
}

void show_spc(int n)
{
	int i;
	for (i=0; i<n; i++) show_str(" ");
}

void show_v(int v, int by_asc)
{
	//|-->  only compiler
	printf(by_asc ? "%d" : "%c", v);
	//<--|  // only compiler

	/*-->|  only interpreter
	char *s;
	int i = sys_int(v);
	if (by_asc) s = str(i);
	else s = chr(i);
	stdout_write(s);
	|<--*/  // only interpreter
}

void show_int(int v)
{
	show_v(v, 1);
}

void show_esc(void)
{
	show_v(27, 0);
}

void cls(void)
{
	show_esc();
	show_str("[2J");
}

void locate(int x, int y)
{
	show_esc();
	show_str("[");
	show_int(y+1);
	show_str(";");
	show_int(x+1);
	show_str("H");
}

void show_xy_str(int x, int y, char *s)
{
	locate(x, y);
	show_str(s);
}

//|-->  only compiler

double sys_sec(void)
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return tv.tv_sec + tv.tv_usec * 0.000001;
}

void sys_sleep(double sec)
{
	usleep(sec * 1000000);
}

//<--|  // only compiler

int opt_idx(char *key, int ac, char **av)
{
	int i;
	for (i=0; i<ac; i++) if(strcmp(av[i], key) == 0) return i;
	return -1;
}

char *opt_str(char *key, int ac, char **av, char *def_ret)
{
	int i = opt_idx(key, ac, av);
	if(i < 0 || i+1 >= ac) return def_ret;
	return av[i+1];
}

int opt_int(char *key, int ac, char **av, int def_ret)
{
	char *s = opt_str(key, ac, av, NULL);
	if (s == NULL) return def_ret;
	return atoi(s);
}