#include <stdio.h>
#include "atari.h"
#include "memory.h"
#include "diskled.h"

int led_status = 0;
int led_off_delay = -1;
int led_counter_enabled = 0;
int led_sector = 0;

#define DISKLED_FONT_WIDTH		5
#define DISKLED_FONT_HEIGHT		7
#define DISKLED_FONT_CHARSIZE	(DISKLED_FONT_WIDTH * DISKLED_FONT_HEIGHT)

#define DISKLED_COLOR_READ		0xAC
#define DISKLED_COLOR_WRITE		0x35
#define DISKLED_COLOR_COUNTER	0x88//0x09

static UBYTE DiskLED[] = {
	1,1,1,1,1,
	1,1,0,1,1,
	1,0,1,0,1,
	1,0,1,0,1,
	1,0,1,0,1,
	1,1,0,1,1,
	1,1,1,1,1,

	1,1,1,1,1,
	1,1,0,1,1,
	1,0,0,1,1,
	1,1,0,1,1,
	1,1,0,1,1,
	1,1,0,1,1,
	1,1,1,1,1,

	1,1,1,1,1,
	1,0,0,1,1,
	1,1,1,0,1,
	1,1,0,1,1,
	1,0,1,1,1,
	1,0,0,0,1,
	1,1,1,1,1,

	1,1,1,1,1,
	1,0,0,1,1,
	1,1,1,0,1,
	1,1,0,1,1,
	1,1,1,0,1,
	1,0,0,1,1,
	1,1,1,1,1,

	1,1,1,1,1,
	1,1,1,0,1,
	1,1,0,0,1,
	1,0,1,0,1,
	1,0,0,0,1,
	1,1,1,0,1,
	1,1,1,1,1,

	1,1,1,1,1,
	1,0,0,0,1,
	1,0,1,1,1,
	1,0,0,0,1,
	1,1,1,0,1,
	1,0,0,1,1,
	1,1,1,1,1,

	1,1,1,1,1,
	1,1,0,1,1,
	1,0,1,1,1,
	1,0,0,1,1,
	1,0,1,0,1,
	1,1,0,1,1,
	1,1,1,1,1,

	1,1,1,1,1,
	1,0,0,0,1,
	1,1,1,0,1,
	1,1,0,1,1,
	1,1,0,1,1,
	1,1,0,1,1,
	1,1,1,1,1,

	1,1,1,1,1,
	1,1,0,1,1,
	1,0,1,0,1,
	1,1,0,1,1,
	1,0,1,0,1,
	1,1,0,1,1,
	1,1,1,1,1,

	1,1,1,1,1,
	1,1,0,1,1,
	1,0,1,0,1,
	1,1,0,0,1,
	1,1,1,0,1,
	1,1,0,1,1,
	1,1,1,1,1
};

void LED_Frame(void)
{
	if (led_off_delay >= 0)
		if (--led_off_delay < 0)
			led_status = 0;
#ifndef NO_LED_ON_SCREEN
	if (led_status) {
		UBYTE *screen = (UBYTE *) atari_screen
						+ (screen_visible_y2 - DISKLED_FONT_HEIGHT) * ATARI_WIDTH
						+ screen_visible_x2;
		UBYTE *source = DiskLED + (led_status % 9) * DISKLED_FONT_CHARSIZE;
		UBYTE *target = screen - DISKLED_FONT_WIDTH;

		UBYTE color = led_status < 10 ? DISKLED_COLOR_READ : DISKLED_COLOR_WRITE;
		int x, y;

		for (y = 0; y < DISKLED_FONT_HEIGHT; y++) {
			for (x = 0; x < DISKLED_FONT_WIDTH; x++)
				*target++ = (UBYTE)(*source++ ? color : 0);
			target += ATARI_WIDTH - DISKLED_FONT_WIDTH;
		}

		if (led_counter_enabled) {
			char sector[6];
			int len, i;

			sprintf(sector, "%d", led_sector);
			len = strlen(sector);

			for (i = 0; i < len; i++)
			{
				source = DiskLED + (sector[i] - '0') * DISKLED_FONT_CHARSIZE;
				target = screen - DISKLED_FONT_WIDTH * (len + 1 - i);

				for (y = 0; y < DISKLED_FONT_HEIGHT; y++) {
					for (x = 0; x < DISKLED_FONT_WIDTH; x++)
						*target++ = (UBYTE)(*source++ ? DISKLED_COLOR_COUNTER : 0);
					target += ATARI_WIDTH - DISKLED_FONT_WIDTH;
				}
			}
		}
	}
#endif /* NO_LED_ON_SCREEN */
}
