/* Still Coding in the browser: libatari800 (Atari800, GPL) with its built-in
   AltirraOS, driven one PAL frame at a time from JavaScript. */
#include <emscripten.h>
#include <string.h>
#include "libatari800.h"

extern int Colours_table[256];
static input_template_t input;
static unsigned int rgba[384 * 240];

EMSCRIPTEN_KEEPALIVE int web_init(const char *disk)
{
	char *args[] = {"-xl", "-pal", "-xl-rev", "altirra", "-nobasic", "-dsprate", "44100", "-audio16",
		(char *) disk, NULL};
	int ok = libatari800_init(-1, args);
	libatari800_clear_input_array(&input);
	return ok;
}

/* Atari key code (AKEY_*), 0 = none; joystick bits 1 up 2 down 4 left 8 right. */
EMSCRIPTEN_KEEPALIVE void web_input(int keycode, int joy, int fire)
{
	input.keychar = 0;
	input.keycode = keycode;
	input.joy0 = joy;
	input.trig0 = fire;
}

EMSCRIPTEN_KEEPALIVE unsigned int *web_frame(void)
{
	libatari800_next_frame(&input);
	const unsigned char *s = libatari800_get_screen_ptr();
	for (int i = 0; i < 384 * 240; i++) {
		int c = Colours_table[s[i]];
		rgba[i] = 0xff000000u | ((c & 0xff) << 16) | (c & 0xff00) | ((c >> 16) & 0xff);
	}
	return rgba;
}

EMSCRIPTEN_KEEPALIVE unsigned char *web_sound(void) { return libatari800_get_sound_buffer(); }
EMSCRIPTEN_KEEPALIVE int web_sound_len(void) { return libatari800_get_sound_buffer_len(); }
EMSCRIPTEN_KEEPALIVE int web_sound_rate(void) { return libatari800_get_sound_frequency(); }
EMSCRIPTEN_KEEPALIVE int web_sound_bytes(void) { return libatari800_get_sound_sample_size(); }
EMSCRIPTEN_KEEPALIVE int web_sound_channels(void) { return libatari800_get_num_sound_channels(); }
