/*
 * Apple // emulator for *ix 
 *
 * This software package is subject to the GNU General Public License
 * version 3 or later (your choice) as published by the Free Software
 * Foundation.
 *
 * Copyright 1998, 1999, 2000 Michael Deutschmann
 * Copyright 2013-2015 Aaron Culliney
 *
 */

/*
 * ROM converter
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

static const char *roms[] = {
    NULL,
    "apple_iie_rom",
    "slot6_rom",
    NULL
};
static const char *bools[] = {
    NULL,
    "iie_rom_loaded",
    "slot6_rom_loaded",
    NULL
};
static const size_t sizes[] = {
    0,
    32768,
    256,
    0
};

static void convert_rom(const uint8_t *buf, const size_t len) {
    for (size_t i=0; i<len; i++) {
        uint8_t ch = buf[i];

        if ((i % 16) == 0) {
            printf("\n");
        }

        printf(" 0x%02x", ch);

        if (i < len-1) {
            printf(",");
        }
    }
}

int main(int argc, const char *argv[]) {

    printf("/* Apple II ROM data\n"
           " *\n"
           " * THIS FILE IS AUTOMATICALLY GENERATED --- DO NOT EDIT\n"
           " */\n"
           " \n"
           "#include <stdbool.h>\n"
           "#include <stdint.h>\n");

    FILE *fp = NULL;
    bool error = true;
    uint8_t *buf = NULL;
    size_t num = 0;

    unsigned int idx = 1;
    do {

        printf("\n/* ROM : %s */\n", roms[idx]);
        error = true;
        do {
            if (idx >= argc) {
                fprintf(stderr, "WARNING : rom file unspecified\n");
                break;
            }

            fp = fopen(argv[idx], "r");
            if (!fp) {
                fprintf(stderr, "WARNING : cannot open %s\n", argv[idx]);
                break;
            }

            buf = malloc(sizes[idx]);
            if (!buf) {
                break;
            }

            num = fread(buf, 1, sizes[idx], fp);
            if (num != sizes[idx]) {
                fprintf(stderr, "WARNING : rom file size %u mismatched with expected %u\n", (unsigned int)num, (unsigned int)sizes[idx]);
                break;
            }

            fclose(fp);

            printf("\nbool %s = true;\n", bools[idx]);
            printf("\nuint8_t %s[%u] = {", roms[idx], (unsigned int)sizes[idx]);
            convert_rom(buf, sizes[idx]);
            printf("\n};\n");

            error = false;
        } while(0);

        if (error) {
            printf("\nbool %s = false;\n", bools[idx]);
            printf("\nuint8_t %s[%u] = { 0 };\n", roms[idx], (unsigned int)sizes[idx]);
        }

        if (buf) {
            free(buf);
            buf = NULL;
        }

    } while(roms[++idx] != NULL);

    return 0; // no error so build can continue
}

