#include "../apilib.h"

char string0[256];
char string1[256];

static unsigned char table_rgb[16 * 3] = {
	0x00, 0x00, 0x00,	/*  0:黒 */
	0xff, 0x00, 0x00,	/*  1:明るい赤 */
	0x00, 0xff, 0x00,	/*  2:明るい緑 */
	0xff, 0xff, 0x00,	/*  3:明るい黄色 */
	0x00, 0x00, 0xff,	/*  4:明るい青 */
	0xff, 0x00, 0xff,	/*  5:明るい紫 */
	0x00, 0xff, 0xff,	/*  6:明るい水色 */
	0xff, 0xff, 0xff,	/*  7:白 */
	0xc0, 0xc0, 0xc0,	/*  8:明るい灰色 */
	0x7f, 0x00, 0x00,	/*  9:暗い赤 */
	0x00, 0x7f, 0x00,	/* 10:暗い緑 */
	0x7f, 0x7f, 0x00,	/* 11:暗い黄色 */
	0x00, 0x00, 0x7f,	/* 12:暗い青 */
	0x7f, 0x00, 0x7f,	/* 13:暗い紫 */
	0x00, 0x7f, 0x7f,	/* 14:暗い水色 */
	0x7f, 0x7f, 0x7f	/* 15:暗い灰色 */
};

unsigned int table_8_888[256];
char ifpal_init = 0;

void init_palette(void)
{
	int r, g, b;
	int i;
	
	for (i = 0; i < 16; i++) {
		r = table_rgb[i * 3 + 0];
		g = table_rgb[i * 3 + 1];
		b = table_rgb[i * 3 + 2];
		table_8_888[i] = (((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff));
	}
	for (b = 0; b < 6; b++) {
		for (g = 0; g < 6; g++) {
			for (r = 0; r < 6; r++) {
				table_8_888[r + g * 6 + b * 36 + 16] = ((((r * 51) & 0xff) << 16) | (((g * 51) & 0xff) << 8) | ((b * 51) & 0xff));
			}
		}
	}
	
	
	ifpal_init = 1;
	return;
}

void api_beepEx(int tone, int time)
{
	int timer[2];
	int toneEx = 0;
	timer[0] = api_alloctimer();
	timer[1] = api_alloctimer();
	api_inittimer(timer[0], 32);
	api_inittimer(timer[1], 64);
	toneEx = tone;
	api_settimer(timer[0], time);
	api_beep(0);
	for(;;)
	{
		if(api_getkey(0) == 32) break;
		if(api_getkey(1) == 64) {}
		api_beep(toneEx);
		toneEx--;
		if(toneEx + 10 == tone) toneEx = tone;
	}
	api_beep(0);
	api_freetimer(timer[0]);
	api_freetimer(timer[1]);
}

int api_getint(unsigned char c)
{
	if(ifpal_init != 1)init_palette();
	
	return table_8_888[c];
}

void api_convgrp(char *filename, int *graphbuf)
{
	int fh = api_fopen(filename);
	int c;
	int i = 0;
	
	if (fh != 0) {
		for (;;) {
			if (api_fread(&c, 4, fh) == 0) {
				break;
			}
			graphbuf[i] = c;
			i++;
		}
	} else {
		return;
	}
	
	api_fclose(fh);
}

void api_beep8(struct ENV env, int tone, int time)
{
	int timer[2];
	int tone8 = 0;
	int i = 0;
	timer[0] = api_alloctimer();
	timer[1] = api_alloctimer();
	api_inittimer(timer[0], 32);
	api_inittimer(timer[1], 64);
	tone8 = tone;
	api_settimer(timer[0], time);
	api_settimer(timer[1], 1);
	api_beep(0);
	for(;;)
	{
		api_beep(tone8);
		if(api_getkey(0) == 32) break;
		if(api_getkey(1) == 64);
		api_settimer(timer[1], 1);
		tone8 = tone + env.offset[i] * 1000;
		i++;
	}
	api_beep(0);
	api_freetimer(timer[0]);
	api_freetimer(timer[1]);
}

char *api_getargs(int index)
{
	char *p;
	int n;
	
	api_cmdline(string0,256);
	
	p = string0;
	
	for(n = 0; n < index; n++) {
		for(;*p != ' ';p++);
		if(*p == ' ') p++;
	}
	
	for(n = 0;*p != ' ' && *p != 0;p++,n++) {
		string1[n] = *p;
	}
	
	string1[n] = 0;
	
	return string1;
}
