
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <array>
#include <assert.h>
#include <inttypes.h>
#include <memory>

#include "../../file_io.h"
#include "../../user_io.h"
#include "../../spi.h"
#include "../../hardware.h"
#include "../../menu.h"
#include "cdi.h"
#include "../../cd.h"
#include "../chd/mister_chd.h"
#include <libchdr/chd.h>
#include <arpa/inet.h>

static constexpr auto SERVO_AUDIO_CD_OPT = "[12]";

/// It is written, only on CD-i, this data can be found at timecode 00:02:16
static const uint8_t mode2_bootheader[] = {
	0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, // Sync words
	0x00, 0x02, 0x16														// MSF
};

struct subcode
{
	uint16_t control;
	uint16_t track;
	uint16_t index;
	uint16_t mode1_mins;
	uint16_t mode1_secs;
	uint16_t mode1_frac;
	uint16_t mode1_zero;
	uint16_t mode1_amins;
	uint16_t mode1_asecs;
	uint16_t mode1_afrac;
	uint16_t mode1_crc0;
	uint16_t mode1_crc1;
};
static_assert(sizeof(struct subcode) == CDI_SUBCHANNEL_LEN);

struct toc_entry
{
	uint8_t control;
	uint8_t track;
	uint8_t m;
	uint8_t s;
	uint8_t f;
};

static std::array<struct toc_entry, 200> toc_buffer;
uint32_t toc_entry_count = 0;
static enum DiscType disc_type = DT_CDDA;

static uint8_t *chd_hunkbuf = NULL;
static int chd_hunknum;

static int sgets(char *out, int sz, char **in)
{
	*out = 0;
	do
	{
		char *instr = *in;
		int cnt = 0;

		while (*instr && *instr != 10)
		{
			if (*instr == 13)
			{
				instr++;
				continue;
			}

			if (cnt < sz - 1)
			{
				out[cnt++] = *instr;
				out[cnt] = 0;
			}

			instr++;
		}

		if (*instr == 10)
			instr++;
		*in = instr;
	} while (!*out && **in);

	return *out;
}

static void unload_chd(toc_t *table)
{
	if (table->chd_f)
	{
		chd_close(table->chd_f);
	}
	if (chd_hunkbuf)
		free(chd_hunkbuf);
	memset(table, 0, sizeof(toc_t));
	chd_hunknum = -1;
}

static void unload_cue(toc_t *table)
{
	for (int i = 0; i < table->last; i++)
	{
		FileClose(&table->tracks[i].f);
	}
	memset(table, 0, sizeof(toc_t));
}

static int load_chd(const char *filename, toc_t *table)
{

	unload_chd(table);
	chd_error err = mister_load_chd(filename, table);
	if (err != CHDERR_NONE)
	{
		return 0;
	}

	for (int i = 0; i < table->last; i++)
	{
		table->tracks[i].pregap = table->tracks[i].indexes[1];
		table->tracks[i].start += 150;
		table->tracks[i].end += 150;

		printf("\x1b[32mCHD: Track = %u, start = %u, end = %u, offset = %d, sector_size=%d, type = %u, pregap = %u\n\x1b[0m", i, table->tracks[i].start, table->tracks[i].end, table->tracks[i].offset, table->tracks[i].sector_size, table->tracks[i].type, table->tracks[i].pregap);
		printf("\x1b[32mCHD: Track = %u, Index %u %u seconds\n\x1b[0m", i, table->tracks[i].indexes[0], table->tracks[i].indexes[1]);
	}

	table->end += 150;

	chd_hunkbuf = (uint8_t *)malloc(table->chd_hunksize);
	chd_hunknum = -1;

	return 1;
}

static int load_cue(const char *filename, toc_t *table)
{
	static char fname[1024 + 10];
	static char line[128];
	char *ptr, *lptr;
	static char toc[100 * 1024];

	unload_cue(table);
	printf("\x1b[32mCDI: Open CUE: %s\n\x1b[0m", fname);

	strcpy(fname, filename);

	memset(toc, 0, sizeof(toc));
	if (!FileLoad(fname, toc, sizeof(toc) - 1))
	{
		printf("\x1b[32mCDI: cannot load file: %s\n\x1b[0m", fname);
		return 0;
	}

	int mm, ss, bb;
	int index0 = 0;
	int index1 = 0;

	char *buf = toc;
	while (sgets(line, sizeof(line), &buf))
	{
		lptr = line;
		while (*lptr == 0x20)
			lptr++;

		/* decode FILE commands */
		if (!(memcmp(lptr, "FILE", 4)))
		{
			ptr = fname + strlen(fname) - 1;
			while ((ptr - fname) && (*ptr != '/') && (*ptr != '\\'))
				ptr--;
			if (ptr - fname)
				ptr++;

			lptr += 4;
			while (*lptr == 0x20)
				lptr++;

			if (*lptr == '\"')
			{
				lptr++;
				while ((*lptr != '\"') && (lptr <= (line + 128)) && (ptr < (fname + 1023)))
					*ptr++ = *lptr++;
			}
			else
			{
				while ((*lptr != 0x20) && (lptr <= (line + 128)) && (ptr < (fname + 1023)))
					*ptr++ = *lptr++;
			}
			*ptr = 0;

			if (!FileOpen(&table->tracks[table->last].f, fname))
				return 0;

			printf("\x1b[32mCDI: Open track file: %s\n\x1b[0m", fname);

			table->tracks[table->last].offset = 0;

			if (!strstr(lptr, "BINARY"))
			{
				FileClose(&table->tracks[table->last].f);
				printf("\x1b[32mCDI: unsupported file: %s\n\x1b[0m", fname);
				return 0;
			}
		}

		/* decode PREGAP commands */
		else if (sscanf(lptr, "PREGAP %02d:%02d:%02d", &mm, &ss, &bb) == 3)
		{
			// TODO Find an example image
		}
		/* decode TRACK commands */
		else if ((sscanf(lptr, "TRACK %02d %*s", &bb)) || (sscanf(lptr, "TRACK %d %*s", &bb)))
		{
			index0 = 0;
			if (bb != (table->last + 1))
			{
				FileClose(&table->tracks[table->last].f);
				printf("\x1b[32mCDI: missing tracks: %s\n\x1b[0m", fname);
				return 0;
			}
			bool mode1{strstr(lptr, "MODE1/2352") != nullptr};
			bool mode2{strstr(lptr, "MODE2/2352") != nullptr};
			bool modecdi{strstr(lptr, "CDI/2352") != nullptr};
			bool audio{strstr(lptr, "AUDIO") != nullptr};

			table->tracks[table->last].sector_size = CDI_SECTOR_LEN;
			if (!table->last)
				table->end = 150; // implicit 2 seconds pregap for track 1

			if (mode1)
				table->tracks[table->last].type = TT_MODE1;
			else if (mode2 || modecdi)
				table->tracks[table->last].type = TT_MODE2;
			else if (audio)
				table->tracks[table->last].type = TT_CDDA;
			else
			{
				FileClose(&table->tracks[table->last].f);
				printf("\x1b[32mCDI: unsupported track type: %s\n\x1b[0m", lptr);
				return 0;
			}
		}

		/* decode INDEX commands */
		else if ((sscanf(lptr, "INDEX 00 %02d:%02d:%02d", &mm, &ss, &bb) == 3) ||
				 (sscanf(lptr, "INDEX 0 %02d:%02d:%02d", &mm, &ss, &bb) == 3))
		{
			index0 = bb + ss * 75 + mm * 60 * 75;
		}
		else if ((sscanf(lptr, "INDEX 01 %02d:%02d:%02d", &mm, &ss, &bb) == 3) ||
				 (sscanf(lptr, "INDEX 1 %02d:%02d:%02d", &mm, &ss, &bb) == 3))
		{
			index1 = bb + ss * 75 + mm * 60 * 75;

			if (!table->tracks[table->last].f.opened())
			{
				table->tracks[table->last].start = index1 + 150;
				table->tracks[table->last].pregap = index1 - index0;
				// Subtract the fake 150 sector pregap used for the first data track
				table->tracks[table->last].offset = index0 * table->tracks[table->last].sector_size;
				table->tracks[table->last - 1].end = table->tracks[table->last].start - 1 - table->tracks[table->last].pregap;
			}
			else
			{
				table->tracks[table->last].start = table->end + index0 + index1;
				table->tracks[table->last].pregap = index1 - index0;
				table->end += (table->tracks[table->last].f.size / table->tracks[table->last].sector_size);
				table->tracks[table->last].offset = 0;
			}
			table->tracks[table->last].end = table->end - 1;
			table->last++;
			if (table->last >= 99)
				break;
		}
	}

	for (int i = 0; i < table->last; i++)
	{
		printf("\x1b[32mCUE: Track = %u, start = %u, end = %u, offset = %d, sector_size=%d, type = %u, pregap = %u\n\x1b[0m", i, table->tracks[i].start, table->tracks[i].end, table->tracks[i].offset, table->tracks[i].sector_size, table->tracks[i].type, table->tracks[i].pregap);
	}

	return 1;
}

static int load_cd_image(const char *filename, toc_t *table)
{
	int result = 0;

	const char *ext = strrchr(filename, '.');
	if (!ext)
		return 0;

	if (!strncasecmp(".chd", ext, 4))
	{
		result = load_chd(filename, table);
	}
	else if (!strncasecmp(".cue", ext, 4))
	{
		result = load_cue(filename, table);
	}

	// On a CDI 210/05 the SERVO has to provide the info
	// on whether this is an Audio CD to the SLAVE,
	// which then gives the info to the CDIC driver running on the main CPU.
	// The real source and how this is calculated is yet unknown
	// We use sector 00:02:16 as reference as it contains the boot block.
	// If this is a suitable MODE2 header, we assume it is a CD-i disc
	auto buffer = std::make_unique<uint8_t[]>(CDI_CDIC_BUFFER_SIZE);
	if (buffer)
	{
		cdi_read_cd(buffer.get(), 166, 1);
		bool is_audio_cd = memcmp(buffer.get(), mode2_bootheader, sizeof(mode2_bootheader));
		printf("Is audio CD %d\n", is_audio_cd);
		user_io_status_set(SERVO_AUDIO_CD_OPT, is_audio_cd ? 1 : 0);
	}

	/*
	 * The Disc Type in the TOC needs to be correct for some applications.
	 * For calculation, we use the same algorithm, used by cdrdao
	 * https://github.com/cdrdao/cdrdao/blob/87a1db17571162803d62fb058d911c17ba93e18e/trackdb/Cue2Toc.cc#L666C26-L666C48
	 * CD_DA      only audio
	 * CD_ROM     only mode1 with or without audio
	 * CD_ROM_XA  only mode2 with or without audio
	 * There is also the CDI disc type, though it seems that most burning software
	 * doesn't support it. And - so far - all my discs worked on real hardware.
	 * So we avoid using DT_CDI for now...
	 */
	bool audio{false};
	bool mode1{false};
	bool mode2{false};
	for (int i = 0; i < table->last; i++)
	{
		switch (table->tracks[i].type)
		{
		case TT_CDDA:
			audio = true;
			break;
		case TT_MODE1:
			mode1 = true;
			break;
		case TT_MODE2:
			mode2 = true;
			break;
		}
	}

	if (audio && !mode1 && !mode2)
		disc_type = DT_CDDA;
	else if ((audio && mode1 && !mode2) || (!audio && mode1 && !mode2))
		disc_type = DT_CDROM;
	else if ((audio && !mode1 && mode2) || (!audio && !mode1 && mode2))
		disc_type = DT_CDROMXA;
	// printf("Disc Type %d%d%d %x\n", audio, mode1, mode2, disc_type);
	return result;
}

static void prepare_toc_buffer(toc_t *toc)
{
	struct toc_entry *toc_ptr = toc_buffer.data();
	toc_entry_count = 0;

	auto add_entry = [&](uint8_t control, uint8_t track, uint8_t m, uint8_t s, uint8_t f)
	{
		for (int i = 0; i < 3; i++)
		{
			toc_ptr->control = control;
			toc_ptr->track = track;
			toc_ptr->m = m;
			toc_ptr->s = s;
			toc_ptr->f = f;

			toc_ptr++;

			if (toc_entry_count < toc_buffer.size())
				toc_entry_count++;
		}
	};

	for (int i = 0; i < toc->last; i++)
	{
		int lba = toc->tracks[i].start;
		uint8_t m, s, f;
		m = lba / (60 * 75);
		lba -= m * (60 * 75);
		s = lba / 75;
		f = lba % 75;
		add_entry((toc->tracks[i].type ? 0x41 : 0x01), BCD(i + 1), BCD(m), BCD(s), BCD(f));
	}

	add_entry(1, 0xA0, 1, disc_type, 0);
	add_entry(1, 0xA1, BCD(toc->last), 0, 0);

	{
		int lba = toc->end;
		uint8_t m, s, f;
		m = lba / (60 * 75);
		lba -= m * (60 * 75);
		s = lba / 75;
		f = lba % 75;
		add_entry(1, 0xA2, BCD(m), BCD(s), BCD(f));
	}
}

#define TIMEKEEPER_SIZE (8 * 1024)

static void cdi_mount_save(const char *filename)
{
	user_io_set_index(1);
	if (strlen(filename))
	{
		char buf[1000];
		FileGenerateSavePath(filename, buf, 0);
		user_io_file_mount(buf, 1, 1, TIMEKEEPER_SIZE);
		StoreIdx_S(1, buf);
	}
	else
	{
		user_io_file_mount("", 1);
		StoreIdx_S(1, "");
	}
}

static toc_t toc = {};

int cdi_chd_hunksize()
{
	if (toc.chd_f)
		return toc.chd_hunksize;

	return 0;
}

// CRC routine from https://github.com/mamedev/mame/blob/master/src/mame/philips/cdicdic.cpp
const uint16_t s_crc_ccitt_table[256] =
	{
		0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
		0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
		0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
		0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
		0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
		0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
		0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
		0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
		0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
		0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
		0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
		0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
		0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
		0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
		0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
		0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
		0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
		0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
		0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
		0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
		0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
		0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
		0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
		0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
		0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
		0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
		0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
		0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
		0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
		0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
		0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
		0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0};

#define CRC_CCITT_ROUND(accum, data) (((accum << 8) | data) ^ s_crc_ccitt_table[accum >> 8])

// sector descrambling routine from https://github.com/mamedev/mame/blob/master/src/mame/philips/cdicdic.cpp
const uint8_t s_sector_scramble[] =
	{
		0x01, 0x80, 0x00, 0x60, 0x00, 0x28, 0x00, 0x1e, 0x80, 0x08, 0x60, 0x06, 0xa8, 0x02, 0xfe, 0x81,
		0x80, 0x60, 0x60, 0x28, 0x28, 0x1e, 0x9e, 0x88, 0x68, 0x66, 0xae, 0xaa, 0xfc, 0x7f, 0x01, 0xe0,
		0x00, 0x48, 0x00, 0x36, 0x80, 0x16, 0xe0, 0x0e, 0xc8, 0x04, 0x56, 0x83, 0x7e, 0xe1, 0xe0, 0x48,
		0x48, 0x36, 0xb6, 0x96, 0xf6, 0xee, 0xc6, 0xcc, 0x52, 0xd5, 0xfd, 0x9f, 0x01, 0xa8, 0x00, 0x7e,
		0x80, 0x20, 0x60, 0x18, 0x28, 0x0a, 0x9e, 0x87, 0x28, 0x62, 0x9e, 0xa9, 0xa8, 0x7e, 0xfe, 0xa0,
		0x40, 0x78, 0x30, 0x22, 0x94, 0x19, 0xaf, 0x4a, 0xfc, 0x37, 0x01, 0xd6, 0x80, 0x5e, 0xe0, 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0x55, 0xfb, 0x7f, 0x03, 0x60,
		0x01, 0xe8, 0x00, 0x4e, 0x80, 0x34, 0x60, 0x17, 0x68, 0x0e, 0xae, 0x84, 0x7c, 0x63, 0x61, 0xe9,
		0xe8, 0x4e, 0xce, 0xb4, 0x54, 0x77, 0x7f, 0x66, 0xa0, 0x2a, 0xf8, 0x1f, 0x02, 0x88, 0x01, 0xa6,
		0x80, 0x7a, 0xe0, 0x23, 0x08, 0x19, 0xc6, 0x8a, 0xd2, 0xe7, 0x1d, 0x8a, 0x89, 0xa7, 0x26, 0xfa,
		0x9a, 0xc3, 0x2b, 0x11, 0xdf, 0x4c, 0x58, 0x35, 0xfa, 0x97, 0x03, 0x2e, 0x81, 0xdc, 0x60, 0x59,
		0xe8, 0x3a, 0xce, 0x93, 0x14, 0x6d, 0xcf, 0x6d, 0x94, 0x2d, 0xaf, 0x5d, 0xbc, 0x39, 0xb1, 0xd2,
		0xf4, 0x5d, 0x87, 0x79, 0xa2, 0xa2, 0xf9, 0xb9, 0x82, 0xf2, 0xe1, 0x85, 0x88, 0x63, 0x26, 0xa9,
		0xda, 0xfe, 0xdb, 0x00, 0x5b, 0x40, 0x3b, 0x70, 0x13, 0x64, 0x0d, 0xeb, 0x45, 0x8f, 0x73, 0x24,
		0x25, 0xdb, 0x5b, 0x1b, 0x7b, 0x4b, 0x63, 0x77, 0x69, 0xe6, 0xae, 0xca, 0xfc, 0x57, 0x01, 0xfe,
		0x80, 0x40, 0x60, 0x30, 0x28, 0x14, 0x1e, 0x8f, 0x48, 0x64, 0x36, 0xab, 0x56, 0xff, 0x7e, 0xc0,
		0x20, 0x50, 0x18, 0x3c, 0x0a, 0x91, 0xc7, 0x2c, 0x52, 0x9d, 0xfd, 0xa9, 0x81, 0xbe, 0xe0, 0x70,
		0x48, 0x24, 0x36, 0x9b, 0x56, 0xeb, 0x7e, 0xcf, 0x60, 0x54, 0x28, 0x3f, 0x5e, 0x90, 0x38, 0x6c,
		0x12, 0xad, 0xcd, 0x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x82, 0x98, 0x61, 0xaa, 0xa8, 0x7f, 0x3e,
		0xa0, 0x10, 0x78, 0x0c, 0x22, 0x85, 0xd9, 0xa3, 0x1a, 0xf9, 0xcb, 0x02, 0xd7, 0x41, 0x9e, 0xb0,
		0x68, 0x74, 0x2e, 0xa7, 0x5c, 0x7a, 0xb9, 0xe3, 0x32, 0xc9, 0xd5, 0x96, 0xdf, 0x2e, 0xd8, 0x1c,
		0x5a, 0x89, 0xfb, 0x26, 0xc3, 0x5a, 0xd1, 0xfb, 0x1c, 0x43, 0x49, 0xf1, 0xf6, 0xc4, 0x46, 0xd3,
		0x72, 0xdd, 0xe5, 0x99};

void descramble_sector(uint8_t *buffer)
{
	for (uint32_t i = 12; i < CDI_SECTOR_LEN; i++)
	{
		buffer[i] ^= s_sector_scramble[i - 12];
	}
}

static inline uint32_t unBCD(uint32_t val)
{
	return ((val & 0xf0) >> 4) * 10 + (val & 0x0f);
}

void check_scramble(int lba, uint8_t *buffer)
{
	// Check for sync pattern to confirm mode 2
	// Starts and ends with 0x00 and ...
	if ((buffer[0] != 0) || (buffer[11] != 0))
		return;

	// ... inbetween there are 0xff bytes
	for (uint32_t i = 01; i < 11; i++)
		if (buffer[i] != 0xff)
			return;

	// Sync pattern confirmed. check validity of mode2 header
	uint32_t mm, ss, ff;
	uint8_t mode;

	mm = unBCD(buffer[12]);
	ss = unBCD(buffer[13]);
	ff = unBCD(buffer[14]);
	mode = buffer[15];
	int mode2_lba = mm * 75 * 60 + ss * 75 + ff;

	if (mode2_lba == lba && mode == 2)
	{
		// Is a valid header. Do nothing
	}
	else
	{
		// Can we fix it? Let's test on 4 bytes
		mm = unBCD(buffer[12] ^ s_sector_scramble[0]);
		ss = unBCD(buffer[13] ^ s_sector_scramble[1]);
		ff = unBCD(buffer[14] ^ s_sector_scramble[2]);
		mode = buffer[15] ^ s_sector_scramble[3];
		mode2_lba = mm * 75 * 60 + ss * 75 + ff;
		if (mode2_lba == lba && mode == 2)
		{
			descramble_sector(buffer);
		}
	}
}

void subcode_data(int lba, struct subcode &out)
{
	if (lba < 0)
	{
		// TOC is expected by the core at lba -65536
		lba += 65536;

		uint8_t am, as, af;
		am = lba / (60 * 75);
		int rem_lba = lba - am * (60 * 75);
		as = rem_lba / 75;
		af = rem_lba % 75;

		if (toc_entry_count == 0) // catch division by zero
			return;
		auto &toc_entry = toc_buffer[lba % toc_entry_count];

		out.control = htons(toc_entry.control);
		out.track = 0; // Track 0 for TOC
		out.index = htons(toc_entry.track);
		out.mode1_mins = htons(BCD(am));
		out.mode1_secs = htons(BCD(as));
		out.mode1_frac = htons(BCD(af));
		out.mode1_zero = 0;
		out.mode1_amins = htons(toc_entry.m);
		out.mode1_asecs = htons(toc_entry.s);
		out.mode1_afrac = htons(toc_entry.f);
		out.mode1_crc0 = htons(0xff);
		out.mode1_crc1 = htons(0xff);
	}
	else
	{
		uint8_t am, as, af;
		am = lba / (60 * 75);
		int rem_lba = lba - am * (60 * 75);
		as = rem_lba / 75;
		af = rem_lba % 75;

		int track = toc.GetTrackByLBA(lba + 150);

		int track_lba = 0;
		if (track < (int)ARRAY_LENGTH(toc.tracks))
			track_lba = lba - toc.tracks[track].start;

		int index = 1;

		if (track_lba < 0)
		{
			// Fix index 0 tracks which are defined as pause
			// The timecode seems to go backwards on a real machine
			track_lba = -track_lba;
			index = 0;
		};

		uint8_t tm, ts, tf;
		tm = track_lba / (60 * 75);
		track_lba -= tm * (60 * 75);
		ts = track_lba / 75;
		tf = track_lba % 75;

		if (track < (int)ARRAY_LENGTH(toc.tracks))
			out.control = htons(toc.tracks[track].type ? 0x41 : 0x01);
		out.track = htons(BCD(track + 1));
		out.index = htons(BCD(index));
		out.mode1_mins = htons(BCD(tm));
		out.mode1_secs = htons(BCD(ts));
		out.mode1_frac = htons(BCD(tf));
		out.mode1_zero = 0;
		out.mode1_amins = htons(BCD(am));
		out.mode1_asecs = htons(BCD(as));
		out.mode1_afrac = htons(BCD(af));
		out.mode1_crc0 = htons(0xff);
		out.mode1_crc1 = htons(0xff);
	}

	uint16_t crc_accum = 0;
	uint8_t *crc = reinterpret_cast<uint8_t *>(&out);
	for (int i = 0; i < 12; i++)
		crc_accum = CRC_CCITT_ROUND(crc_accum, crc[1 + i * 2]);

	out.mode1_crc0 = htons((crc_accum >> 8) & 0xff);
	out.mode1_crc1 = htons(crc_accum & 0xff);
#if 0
	printf("subcode %d   %02x %02x %02x %02x %02x %02x     %02x %02x %02x %02x %02x %02x\n", lba,
		   ntohs(out.control), ntohs(out.track), ntohs(out.index),
		   ntohs(out.mode1_mins), ntohs(out.mode1_secs), ntohs(out.mode1_frac), ntohs(out.mode1_zero),
		   ntohs(out.mode1_amins), ntohs(out.mode1_asecs), ntohs(out.mode1_afrac), ntohs(out.mode1_crc0),
		   ntohs(out.mode1_crc1));
#endif
}

void cdi_read_cd(uint8_t *buffer, int lba, int cnt)
{
	int calc_lba = lba;
	uint8_t am, as, af;
	am = calc_lba / (60 * 75);
	calc_lba -= am * (60 * 75);
	as = calc_lba / 75;
	af = calc_lba % 75;

	printf("req lba=%d, cnt=%d   %02d:%02d:%02d   %d %d\n", lba, cnt, am, as, af,
		   toc.tracks[0].start, toc.tracks[0].pregap);

	while (cnt > 0)
	{
		if (lba < 0 || !toc.last)
		{
			// Probably TOC area
			memset(buffer, 0, CDI_SECTOR_LEN);
			buffer += CDI_SECTOR_LEN;
			subcode_data(lba, *reinterpret_cast<struct subcode *>(buffer));
			buffer += sizeof(struct subcode);
		}
		else
		{
			memset(buffer, 0xAA, CDI_SECTOR_LEN);

			for (int i = 0; i < toc.last; i++)
			{
				if (lba >= (toc.tracks[i].start - toc.tracks[i].pregap) && lba <= toc.tracks[i].end)
				{
					if (!toc.chd_f)
					{
						if (toc.tracks[i].offset)
						{
							FileSeek(&toc.tracks[0].f, toc.tracks[i].offset + ((lba - toc.tracks[i].start + toc.tracks[i].pregap) * CDI_SECTOR_LEN), SEEK_SET);
						}
						else
						{
							FileSeek(&toc.tracks[i].f, (lba - toc.tracks[i].start + toc.tracks[i].pregap) * CDI_SECTOR_LEN, SEEK_SET);
						}
					}

					while (cnt)
					{
						if (toc.chd_f)
						{
							// The "fake" 150 sector pregap moves all the LBAs up by 150, so adjust here to read where the core actually wants data from
							int read_lba = lba - 150;
							if (mister_chd_read_sector(toc.chd_f, (read_lba + toc.tracks[i].offset), 0, 0, CDI_SECTOR_LEN, buffer, chd_hunkbuf, &chd_hunknum) == CHDERR_NONE)
							{
								if (!toc.tracks[i].type) // CHD requires byteswap of audio data
								{
									for (int swapidx = 0; swapidx < CDI_SECTOR_LEN; swapidx += 2)
									{
										uint8_t temp = buffer[swapidx];
										buffer[swapidx] = buffer[swapidx + 1];
										buffer[swapidx + 1] = temp;
									}
								}
							}
							else
							{
								printf("\x1b[32mCDI: CHD read error: %d\n\x1b[0m", lba);
							}
						}
						else
						{
							if (toc.tracks[i].offset)
								FileReadAdv(&toc.tracks[0].f, buffer, CDI_SECTOR_LEN);
							else
								FileReadAdv(&toc.tracks[i].f, buffer, CDI_SECTOR_LEN);
						}
						if ((lba + 1) > toc.tracks[i].end)
							break;

						check_scramble(lba, buffer);
						buffer += CDI_SECTOR_LEN;
						subcode_data(lba, *reinterpret_cast<struct subcode *>(buffer));
						buffer += sizeof(struct subcode);
						cnt--;
						lba++;
					}
					break;
				}
			}
		}

		buffer += CDI_SECTOR_LEN;
		buffer += sizeof(struct subcode);
		cnt--;
		lba++;
	}
}

static void mount_cd(int size, int index)
{
	spi_uio_cmd_cont(UIO_SET_SDINFO);
	spi32_w(size);
	spi32_w(0);
	DisableIO();
	spi_uio_cmd8(UIO_SET_SDSTAT, (1 << index) | 0x80);
	user_io_bufferinvalidate(0);
}

/// Last used directory for save file management
/// Must be static to keep the value between mount calls
static char last_dir[1024] = "";

void cdi_mount_cd(int s_index, const char *filename)
{
	int loaded = 0;

	if (strlen(filename))
	{
		if (load_cd_image(filename, &toc) && toc.last)
		{
			const char *p = strrchr(filename, '/');
			int cur_len = p ? p - filename : 0;
			int old_len = strlen(last_dir);

			int same_game = old_len && (cur_len == old_len) && !strncmp(last_dir, filename, old_len);

			// Handle multi disc titles and avoid re-mounting the save file
			// to avoid resets on the core
			if (!same_game)
			{
				strncpy(last_dir, filename, sizeof(last_dir));
				char *p = strrchr(last_dir, '/');
				if (p)
					*p = 0;
				else
					*last_dir = 0;

				// FPGA side will be informed about the mount and perform a reset
				// if configured to do so
				cdi_mount_save(last_dir);
			}

			prepare_toc_buffer(&toc);
			user_io_set_index(0);
			mount_cd(toc.end * CDI_SECTOR_LEN, s_index);
			loaded = 1;
		}
	}

	if (!loaded)
	{
		printf("Unmount CD\n");
		unload_cue(&toc);
		unload_chd(&toc);
		mount_cd(0, s_index);
	}
}

void cdi_poll()
{
}

void cdi_load_root_nvram()
{
	strcpy(last_dir, "games/CD-i");
	cdi_mount_save(last_dir);
}
