/*
 * freezemachine.c - Cartridge handling, Freeze Machine cart.
 *
 * Written by
 *  Groepaz <groepaz@gmx.net>
 *
 * This file is part of VICE, the Versatile Commodore Emulator.
 * See README for copyright notice.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 *  02111-1307  USA.
 *
 */

#include "vice.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define CARTRIDGE_INCLUDE_SLOTMAIN_API
#include "c64cartsystem.h"
#undef CARTRIDGE_INCLUDE_SLOTMAIN_API
#include "c64mem.h"
#include "cartio.h"
#include "cartridge.h"
#include "export.h"
#include "freezemachine.h"
#include "snapshot.h"
#include "types.h"
#include "util.h"
#include "crt.h"

/* #define FMDEBUG */

#ifdef FMDEBUG
#define DBG(x) printf x
#else
#define DBG(x)
#endif

/*
    FIXME: this implementation is based on vague guesses on how the hardware
           really works.

    Evesham Micros "Freeze Frame MK3 v2"

    - 2 Buttons (Freeze, Reset)
    - 16k ROM

    Evesham Micros "Freeze Frame MK4 LAZER", "Freeze Machine"

    - 2 Buttons (Freeze, Reset)
    - 7474, 74163, 2 * 7400, 7402
    - 32k ROM, splitted into 2 16K parts of which 2 8k banks are used at once

    - reading io1 (the software uses de00 only it seems)
      - switches to 16k game mode
      - ROM bank 0 (2) is mapped to 8000
      - ROM bank 1 (3) is mapped to A000

    - reading io2 (the software uses df00 only it seems)
      - disables cartridge ROM

    - reset
      - enables 8K game mode
      - toggles a flipflop which selects wether the upper or lower part of the
        32k ROM is selected. (Freeze Machine only)
      - ROM bank 0 (2) is mapped to 8000

    - freeze
      - enables ultimax mode
      - ROM bank 0 (2) is mapped to 8000
      - ROM bank 0 (2) is mapped to E000
*/

#define FREEZE_MACHINE_CART_SIZE (32 * 0x400)
#define FREEZE_FRAME_MK4_CART_SIZE (16 * 0x400)

static int rom_A14;      /* when set, bank 2 and 3 are active */
static int roml_toggle;  /* when set, bank 1 or 3 will be used for roml */
static int allow_toggle;

/* ---------------------------------------------------------------------*/

static uint8_t freezemachine_io1_read(uint16_t addr)
{
    DBG(("io1 r %04x\n", addr));
    /* if (addr == 0) */ {
        roml_toggle = 1;
        cart_config_changed_slotmain(CMODE_RAM, (uint8_t)(CMODE_16KGAME | (rom_A14 << CMODE_BANK_SHIFT)), CMODE_READ);
        DBG(("Freeze Machine: switching to 16k game mapping\n"));
    }
    return 0; /* invalid */
}

static uint8_t freezemachine_io1_peek(uint16_t addr)
{
    return 0; /* invalid */
}

static void freezemachine_io1_store(uint16_t addr, uint8_t value)
{
    DBG(("io1 w %04x %02x\n", addr, value));
}

static uint8_t freezemachine_io2_read(uint16_t addr)
{
    DBG(("io2 r %04x\n", addr));
    /* if (addr == 0) */ {
        cart_config_changed_slotmain(CMODE_RAM, CMODE_RAM, CMODE_READ);
        DBG(("Freeze Machine: disabled\n"));
    }

    return 0; /* invalid */
}

static uint8_t freezemachine_io2_peek(uint16_t addr)
{
    return 0; /* invalid */
}

static void freezemachine_io2_store(uint16_t addr, uint8_t value)
{
    DBG(("io2 w %04x %02x\n", addr, value));
}

static io_source_t freezemachine_io1_device = {
    CARTRIDGE_NAME_FREEZE_MACHINE, /* name of the device */
    IO_DETACH_CART,                /* use cartridge ID to detach the device when involved in a read-collision */
    IO_DETACH_NO_RESOURCE,         /* does not use a resource for detach */
    0xde00, 0xdeff, 0xff,          /* range for the device, address is ignored, reg:$de00, mirrors:$de01-$deff */
    0,                             /* read is never valid */
    freezemachine_io1_store,       /* store function */
    NULL,                          /* NO poke function */
    freezemachine_io1_read,        /* read function */
    freezemachine_io1_peek,        /* peek function */
    NULL,                          /* TODO: device state information dump function */
    CARTRIDGE_FREEZE_MACHINE,      /* cartridge ID */
    IO_PRIO_NORMAL,                /* normal priority, device read needs to be checked for collisions */
    0                              /* insertion order, gets filled in by the registration function */
};

static io_source_t freezemachine_io2_device = {
    CARTRIDGE_NAME_FREEZE_MACHINE, /* name of the device */
    IO_DETACH_CART,                /* use cartridge ID to detach the device when involved in a read-collision */
    IO_DETACH_NO_RESOURCE,         /* does not use a resource for detach */
    0xdf00, 0xdfff, 0xff,          /* range for the device, address is ignored, reg:$df00, mirrors:$df01-$dfff */
    0,                             /* read is never valid */
    freezemachine_io2_store,       /* store function */
    NULL,                          /* NO poke function */
    freezemachine_io2_read,        /* read function */
    freezemachine_io2_peek,        /* peek function */
    NULL,                          /* TODO: device state information dump function */
    CARTRIDGE_FREEZE_MACHINE,      /* cartridge ID */
    IO_PRIO_NORMAL,                /* normal priority, device read needs to be checked for collisions */
    0                              /* insertion order, gets filled in by the registration function */
};

static io_source_list_t *freezemachine_io1_list_item = NULL;
static io_source_list_t *freezemachine_io2_list_item = NULL;

static const export_resource_t export_res = {
    CARTRIDGE_NAME_FREEZE_MACHINE, 1, 1, &freezemachine_io1_device, &freezemachine_io2_device, CARTRIDGE_FREEZE_MACHINE
};

/* ---------------------------------------------------------------------*/

uint8_t freezemachine_roml_read(uint16_t addr)
{
    if (roml_toggle) {
        return romh_banks[(addr & 0x1fff) | (rom_A14 << 13)];
    }
    return roml_banks[(addr & 0x1fff) | (rom_A14 << 13)];
}

/* ---------------------------------------------------------------------*/

void freezemachine_reset(void)
{
    if (allow_toggle) {
        rom_A14 ^= 1; /* select other 16k ROM bank on every other reset */
    }
    roml_toggle = 0;
    cart_config_changed_slotmain(CMODE_RAM, (uint8_t)(CMODE_8KGAME | (rom_A14 << CMODE_BANK_SHIFT)), CMODE_READ);
    DBG(("Freeze Machine: reset (%d)\n", rom_A14));
}

void freezemachine_freeze(void)
{
    DBG(("Freeze Machine: freeze\n"));
    roml_toggle = 1;
    cart_config_changed_slotmain(CMODE_RAM, (uint8_t)(CMODE_ULTIMAX | (rom_A14 << CMODE_BANK_SHIFT)), CMODE_READ | CMODE_RELEASE_FREEZE);
}

void freezemachine_config_init(void)
{
    cart_config_changed_slotmain(CMODE_RAM, (uint8_t)(CMODE_8KGAME | (rom_A14 << CMODE_BANK_SHIFT)), CMODE_READ);
}

void freezemachine_config_setup(uint8_t *rawcart)
{
    rom_A14 = allow_toggle; /* the following first reset will turn it to 0 again */
    roml_toggle = 0;
    memcpy(roml_banks, rawcart, 0x2000);
    memcpy(romh_banks, &rawcart[0x2000], 0x2000);
    memcpy(&roml_banks[0x2000], &rawcart[0x4000], 0x2000);
    memcpy(&romh_banks[0x2000], &rawcart[0x6000], 0x2000);
    cart_config_changed_slotmain(CMODE_RAM, CMODE_8KGAME | (0 << CMODE_BANK_SHIFT), CMODE_READ);
}

/* ---------------------------------------------------------------------*/

static int freezemachine_common_attach(void)
{
    if (export_add(&export_res) < 0) {
        return -1;
    }

    freezemachine_io1_list_item = io_source_register(&freezemachine_io1_device);
    freezemachine_io2_list_item = io_source_register(&freezemachine_io2_device);

    return 0;
}

int freezemachine_bin_attach(const char *filename, uint8_t *rawcart)
{
    DBG(("Freeze Machine: bin attach '%s'\n", filename));
    allow_toggle = 1;
    if (util_file_load(filename, rawcart, FREEZE_MACHINE_CART_SIZE, UTIL_FILE_LOAD_SKIP_ADDRESS) < 0) {
        if (util_file_load(filename, rawcart, FREEZE_FRAME_MK4_CART_SIZE, UTIL_FILE_LOAD_SKIP_ADDRESS) < 0) {
            return -1;
        }
        allow_toggle = 0;
    }

    return freezemachine_common_attach();
}

/*
 * (old) wrong formats:
 * 
 * cartconv produced this until 2011:
 *
 * offset  sig  type  bank start size  chunklen
 * $000040 CHIP ROM   #000 $8000 $2000 $2010
 * $002050 CHIP ROM   #001 $8000 $2000 $2010
 * $004060 CHIP ROM   #002 $8000 $2000 $2010 (32k ROMs only)
 * $006070 CHIP ROM   #003 $8000 $2000 $2010 (32k ROMs only)
 *
 * cartconv produced this from 2011 to 12/2015:
 *
 * offset  sig  type  bank start size  chunklen
 * $000040 CHIP ROM   #000 $8000 $2000 $2010
 * $002050 CHIP ROM   #000 $a000 $2000 $2010
 * $004060 CHIP ROM   #001 $8000 $2000 $2010 (32k ROMs only)
 * $006070 CHIP ROM   #001 $a000 $2000 $2010 (32k ROMs only)
 *
 * (new) correct format (since 12/2015):
 *
 * offset  sig  type  bank start size  chunklen
 * $000040 CHIP ROM   #000 $8000 $4000 $4010
 * $004050 CHIP ROM   #001 $8000 $4000 $4010 (32k ROMs only)
 *
 */
int freezemachine_crt_attach(FILE *fd, uint8_t *rawcart)
{
    int i, banks, chips;
    size_t pos;
    crt_chip_header_t chip;

    /* find out how many banks and chips are in the file */
    /* FIXME: this is kindof ugly, perhaps make it a generic function */
    banks = 0;
    pos = ftell(fd);
    for (chips = 0; chips < 4; chips++) {
        if (crt_read_chip_header(&chip, fd)) {
            break;
        }
        if (crt_read_chip(rawcart, 0, &chip, fd)) {
            return -1;
        }
        if (chip.bank > banks) {
            banks = chip.bank;
        }
    }
    banks++;
    DBG(("fm attach: %d banks, %d chips found\n", banks, chips));
    if ((chips != 1) && (chips != 2) && (chips != 4)) {
        DBG(("fm attach: wrong number of chips\n"));
        return -1;
    }
    fseek(fd, pos, SEEK_SET);

    for (i = 0; i < chips; i++) {
        if (crt_read_chip_header(&chip, fd)) {
            return -1;
        }
        DBG(("fm attach: chip.size %04x\n", chip.size));
        /* first the new format */
        if ((chip.size == 0x4000) && (((chips == 1) && (banks == 1)) || ((chips == 2) && (banks == 2)))) {
            if ((chip.bank > 1) || (chip.start != 0x8000)) {
                return -1;
            }
            if (crt_read_chip(rawcart, (chip.bank << 14), &chip, fd)) {
                return -1;
            }
            allow_toggle = (chips == 2);
        /* older format */
        } else if ((chip.size == 0x2000) && (((chips == 2) && (banks == 1)) || ((chips == 4) && (banks == 2)))) {
            if ((chip.bank > 1) || ((chip.start != 0x8000) && (chip.start != 0xa000))) {
                return -1;
            }
            if (crt_read_chip(rawcart, (chip.start & 0x2000) + (chip.bank << 14), &chip, fd)) {
                return -1;
            }
            allow_toggle = (chips == 4);
        /* very old format */
        } else if ((chip.size == 0x2000) && (((chips == 2) && (banks == 2)) || ((chips == 4) && (banks == 4)))) {
            if ((chip.bank > 3) || (chip.start != 0x8000)) {
                return -1;
            }
            if (crt_read_chip(rawcart, chip.bank << 13, &chip, fd)) {
                return -1;
            }
            allow_toggle = (chips == 4);
        } else {
            return -1;
        }
    }
    return freezemachine_common_attach();
}

void freezemachine_detach(void)
{
    export_remove(&export_res);
    io_source_unregister(freezemachine_io1_list_item);
    io_source_unregister(freezemachine_io2_list_item);
    freezemachine_io1_list_item = NULL;
    freezemachine_io2_list_item = NULL;
}

/* ---------------------------------------------------------------------*/

/* CARTFREEZEM snapshot module format:

   type  | name         | version | description
   --------------------------------------------
   BYTE  | ROM A14      |   0.0+  | A14 line state
   BYTE  | ROML toggle  |   0.0+  | ROML toggle flag
   BYTE  | allow toggle |   0.1   | allow toggle flag
   ARRAY | ROML         |   0.0+  | 16384 BYTES of ROML data
   ARRAY | ROMH         |   0.0+  | 16384 BYTES of ROMH data
 */

static const char snap_module_name[] = "CARTFREEZEM";
#define SNAP_MAJOR   0
#define SNAP_MINOR   1

int freezemachine_snapshot_write_module(snapshot_t *s)
{
    snapshot_module_t *m;

    m = snapshot_module_create(s, snap_module_name, SNAP_MAJOR, SNAP_MINOR);

    if (m == NULL) {
        return -1;
    }

    if (0
        || SMW_B(m, (uint8_t)rom_A14) < 0
        || SMW_B(m, (uint8_t)roml_toggle) < 0
        || SMW_B(m, (uint8_t)allow_toggle) < 0
        || SMW_BA(m, roml_banks, 0x4000) < 0
        || SMW_BA(m, romh_banks, 0x4000) < 0) {
        snapshot_module_close(m);
        return -1;
    }

    return snapshot_module_close(m);
}

int freezemachine_snapshot_read_module(snapshot_t *s)
{
    uint8_t vmajor, vminor;
    snapshot_module_t *m;

    m = snapshot_module_open(s, snap_module_name, &vmajor, &vminor);

    if (m == NULL) {
        return -1;
    }

    /* Do not accept versions higher than current */
    if (snapshot_version_is_bigger(vmajor, vminor, SNAP_MAJOR, SNAP_MINOR)) {
        snapshot_set_error(SNAPSHOT_MODULE_HIGHER_VERSION);
        goto fail;
    }

    if (0
        || SMR_B_INT(m, &rom_A14) < 0
        || SMR_B_INT(m, &roml_toggle) < 0) {
        goto fail;
    }

    /* new in 0.1 */
    if (!snapshot_version_is_smaller(vmajor, vminor, 0, 1)) {
        if (SMR_B_INT(m, &allow_toggle) < 0) {
            goto fail;
        }
    } else {
        allow_toggle = 0;
    }

    if (0
        || SMR_BA(m, roml_banks, 0x4000) < 0
        || SMR_BA(m, romh_banks, 0x4000) < 0) {
        goto fail;
    }

    snapshot_module_close(m);

    return freezemachine_common_attach();

fail:
    snapshot_module_close(m);
    return -1;
}
