/*
 * File: xex2disk.c
 * Description:
 *   Convert an AtariWars XEX into a three-sector SIO bootloader and a flat
 *   RAM image. sectorCat combines both outputs into the bootable ATR.
 *
 * Usage: xex2disk INPUT.xex BOOT.bin MEMORY.bin
 *
 * Only RAM segments at $2000..$bfff and RUNAD are supported, not INITAD.
 * The bootloader reads disk sectors 4..323, then jumps to the XEX entry point.
 */

#define _CRT_SECURE_NO_WARNINGS

#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum {
    LOAD_ADDRESS = 0x2000,
    RAM_LIMIT = 0xc000,
    BOOT_ADDRESS = 0x0700,
    RUN_ADDRESS = 0x02e0,
    SECTOR_BYTES = 128,
    BOOT_SECTORS = 3,
    BOOT_BYTES = BOOT_SECTORS * SECTOR_BYTES,
    IMAGE_BYTES = RAM_LIMIT - LOAD_ADDRESS,
    IMAGE_SECTORS = IMAGE_BYTES / SECTOR_BYTES
};

/* Same SIO/DCB protocol as Assembler/bootLoader.s, with a 16-bit count.
   The arrays delimit branch targets without hard-coded instruction offsets. */
typedef struct {
    uint8_t header[6];
    uint8_t setup[19];
    uint8_t copy_dcb[9];
    uint8_t read_sector[15];
    uint8_t advance_buffer[11];
    uint8_t buffer_carry[3];
    uint8_t advance_sector[5];
    uint8_t sector_carry[3];
    uint8_t check_counter[4];
    uint8_t counter_borrow[2];
    uint8_t decrement_counter[8];
    uint8_t run[3];
    uint8_t error[6];
    uint8_t dcb[12];
} BootProgram;

#define WORD(value) (uint8_t)((value) & 0xff), (uint8_t)(((value) >> 8) & 0xff)
#define ADDRESS(field) (BOOT_ADDRESS + offsetof(BootProgram, field))
#define RELATIVE(from, to) \
    ((uint8_t)((int)offsetof(BootProgram, to) \
        - (int)(offsetof(BootProgram, from) + sizeof(((BootProgram *)0)->from))))

static BootProgram boot_program = {
    /* Atari boot header: flags, sector count, load address, init address. */
    .header = {
        0, BOOT_SECTORS, WORD(BOOT_ADDRESS), WORD(ADDRESS(setup))
    },

    /* Disable DMA and store the remaining sector count at $cb/$cc. */
    .setup = {
        0xd8,                                  /* CLD */
        0xa9, 0,                               /* LDA #0 */
        0x8d, WORD(0x022f),                     /* STA SDMCTL */
        0x8d, WORD(0xd400),                     /* STA DMACTL */
        0xa9, (uint8_t)(IMAGE_SECTORS & 0xff),   /* LDA #<IMAGE_SECTORS */
        0x85, 0xcb,                            /* STA $cb */
        0xa9, (uint8_t)(IMAGE_SECTORS >> 8),     /* LDA #>IMAGE_SECTORS */
        0x85, 0xcc,                            /* STA $cc */
        0xa2, 11                               /* LDX #11 */
    },

    .copy_dcb = {
        0xbd, WORD(ADDRESS(dcb)),               /* LDA dcb,X */
        0x9d, WORD(0x0300),                     /* STA DCB,X */
        0xca,                                  /* DEX */
        0x10, RELATIVE(copy_dcb, copy_dcb)       /* BPL copy_dcb */
    },

    /* DSTATS must be reset to the read direction before every SIO call. */
    .read_sector = {
        0xa9, 0x40,                            /* LDA #$40 */
        0x8d, WORD(0x0303),                     /* STA DSTATS */
        0x20, WORD(0xe459),                     /* JSR SIOV */
        0xad, WORD(0x0303),                     /* LDA DSTATS */
        0xc9, 1,                               /* CMP #1 */
        0xd0, RELATIVE(read_sector, error)      /* BNE error */
    },

    /* Advance the destination buffer and disk sector, including carries. */
    .advance_buffer = {
        0x18,                                  /* CLC */
        0xad, WORD(0x0304),                     /* LDA DBUFLO */
        0x69, SECTOR_BYTES,                     /* ADC #SECTOR_BYTES */
        0x8d, WORD(0x0304),                     /* STA DBUFLO */
        0x90, RELATIVE(advance_buffer, advance_sector) /* BCC advance_sector */
    },

    .buffer_carry = {
        0xee, WORD(0x0305)                      /* INC DBUFHI */
    },

    .advance_sector = {
        0xee, WORD(0x030a),                     /* INC DAUX1 */
        0xd0, RELATIVE(advance_sector, check_counter) /* BNE check_counter */
    },

    .sector_carry = {
        0xee, WORD(0x030b)                      /* INC DAUX2 */
    },

    /* Decrement the 16-bit count; continue until both bytes are zero. */
    .check_counter = {
        0xa5, 0xcb,                            /* LDA $cb */
        0xd0, RELATIVE(check_counter, decrement_counter) /* BNE decrement_counter */
    },

    .counter_borrow = {
        0xc6, 0xcc                             /* DEC $cc */
    },

    .decrement_counter = {
        0xc6, 0xcb,                            /* DEC $cb */
        0xa5, 0xcb,                            /* LDA $cb */
        0x05, 0xcc,                            /* ORA $cc */
        0xd0, RELATIVE(decrement_counter, read_sector) /* BNE read_sector */
    },

    .run = {
        0x4c, 0, 0                             /* JMP RUNAD; patched from XEX */
    },

    /* Display the SIO error in the background color and halt. */
    .error = {
        0x8d, WORD(0xd01a),                     /* STA COLBK */
        0x4c, WORD(ADDRESS(error))              /* JMP error */
    },

    .dcb = {
        0x31,                                  /* DDEVIC: disk */
        1,                                     /* DUNIT: drive 1 */
        0x52,                                  /* DCOMND: read sector */
        0x40,                                  /* DSTATS: device-to-memory */
        WORD(LOAD_ADDRESS),                    /* DBUFLO/DBUFHI */
        15, 0,                                 /* DTIMLO, unused byte */
        WORD(SECTOR_BYTES),                    /* DBYTLO/DBYTHI */
        BOOT_SECTORS + 1, 0                    /* DAUX1/DAUX2: first data sector */
    },
};

_Static_assert(sizeof(BootProgram) <= BOOT_BYTES, "bootloader exceeds three sectors");
_Static_assert(IMAGE_SECTORS < 65536, "sector counter exceeds 16 bits");

static uint8_t memory_image[IMAGE_BYTES];
static uint8_t loaded_bytes[IMAGE_BYTES];
static const char *input_name;

_Noreturn static void fail(const char *message)
{
    fprintf(stderr, "xex2disk: %s: %s\n", input_name, message);
    exit(EXIT_FAILURE);
}

static unsigned read_word(FILE *input)
{
    int low_byte = fgetc(input);
    int high_byte = fgetc(input);

    if (low_byte == EOF || high_byte == EOF)
    {
        fail("truncated XEX header");
    }

    return (unsigned)low_byte | ((unsigned)high_byte << 8);
}

/* Flatten RAM segments; later segments may overwrite earlier ones.
   RUNAD can arrive as two separate one-byte segments. */
static unsigned load_xex(void)
{
    FILE *input = fopen(input_name, "rb");
    unsigned entry_address = 0;
    unsigned run_address_bytes = 0;
    unsigned segment_count = 0;
    int trailing_separator = 0;

    if (!input)
    {
        fail("cannot open input");
    }
    if (read_word(input) != 0xffff)
    {
        fail("expected XEX $ffff signature");
    }

    for (;;)
    {
        int low_byte = fgetc(input);
        int high_byte;
        unsigned start, end, address;

        if (low_byte == EOF)
        {
            break;
        }

        high_byte = fgetc(input);
        if (high_byte == EOF)
        {
            fail("truncated segment address");
        }

        start = (unsigned)low_byte | ((unsigned)high_byte << 8);
        if (start == 0xffff)
        {
            trailing_separator = 1;
            continue;
        }

        trailing_separator = 0;
        end = read_word(input);

        if (end < start)
        {
            fail("reversed segment");
        }
        if (!((start >= LOAD_ADDRESS && end < RAM_LIMIT)
              || (start >= RUN_ADDRESS && end <= RUN_ADDRESS + 1)))
        {
            fail("only RAM $2000..$bfff and RUNAD are supported; INITAD is not supported");
        }

        for (address = start; address <= end; ++address)
        {
            int value = fgetc(input);

            if (value == EOF)
            {
                fail("truncated segment payload");
            }

            if (address == RUN_ADDRESS)
            {
                entry_address = (entry_address & 0xff00) | (unsigned)value;
                run_address_bytes |= 1;
            }
            else if (address == RUN_ADDRESS + 1)
            {
                entry_address = (entry_address & 0xff) | ((unsigned)value << 8);
                run_address_bytes |= 2;
            }
            else
            {
                memory_image[address - LOAD_ADDRESS] = (uint8_t)value;
                loaded_bytes[address - LOAD_ADDRESS] = 1;
            }
        }

        ++segment_count;
    }

    if (ferror(input))
    {
        fail("input read error");
    }
    if (fclose(input))
    {
        fail("input close error");
    }

    if (!segment_count || trailing_separator || run_address_bytes != 3
        || entry_address < LOAD_ADDRESS || entry_address >= RAM_LIMIT
        || !loaded_bytes[entry_address - LOAD_ADDRESS])
    {
        fail("missing or invalid RUNAD entry point");
    }

    return entry_address;
}

static int write_file(const char *name, const uint8_t *data, size_t size)
{
    FILE *output = fopen(name, "wb");
    int ok;

    if (!output)
    {
        fprintf(stderr, "xex2disk: cannot open output '%s'\n", name);
        return 0;
    }

    ok = fwrite(data, 1, size, output) == size;
    if (fclose(output))
    {
        ok = 0;
    }

    if (!ok)
    {
        fprintf(stderr, "xex2disk: cannot write output '%s'\n", name);
        if (remove(name))
        {
            fprintf(stderr, "xex2disk: cannot remove partial output '%s'\n", name);
        }
    }

    return ok;
}

int main(int argc, char **argv)
{
    uint8_t boot[BOOT_BYTES] = {0};
    unsigned entry_address;

    if (argc != 4)
    {
        fprintf(stderr, "Usage: xex2disk INPUT.xex BOOT.bin MEMORY.bin\n");
        return EXIT_FAILURE;
    }

    input_name = argv[1];
    if (!strcmp(argv[1], argv[2]) || !strcmp(argv[1], argv[3]) || !strcmp(argv[2], argv[3]))
    {
        fail("input and output paths must be different");
    }

    entry_address = load_xex();
    boot_program.run[1] = (uint8_t)entry_address;
    boot_program.run[2] = (uint8_t)(entry_address >> 8);
    memcpy(boot, &boot_program, sizeof(boot_program));

    if (!write_file(argv[2], boot, sizeof(boot)))
    {
        return EXIT_FAILURE;
    }
    if (!write_file(argv[3], memory_image, sizeof(memory_image)))
    {
        return EXIT_FAILURE;
    }

    printf("Disk payload: %d sectors, load $%04x..$%04x, run $%04x\n",
           IMAGE_SECTORS, LOAD_ADDRESS, RAM_LIMIT - 1, entry_address);

    return EXIT_SUCCESS;
}
