/*
Copyright (c) 2021-2025 Rupert Carmichael
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// 93C46 Electrically Erasable Programmable Read-Only Memory

#include <stddef.h>
#include <stdint.h>

#include "eep93c46.h"

/* 93C46B Instruction Set
   ======================================================================
   | Instruction | SB | Opcode |  Address | Data In | Data Out | Cycles |
   ======================================================================
   | ERASE       |  1 | 11     |   A5-A0  | -       | RDY/BSY  | 9      |
   ----------------------------------------------------------------------
   | ERAL        |  1 | 00     | 10xxxxxx | -       | RDY/BSY  | 9      |
   ----------------------------------------------------------------------
   | EWDS        |  1 | 00     | 00xxxxxx | -       | HIGH-Z   | 9      |
   ----------------------------------------------------------------------
   | EWEN        |  1 | 00     | 11xxxxxx | -       | HIGH-Z   | 9      |
   ----------------------------------------------------------------------
   | READ        |  1 | 10     |   A5-A0  | -       | D15-D0   | 25     |
   ----------------------------------------------------------------------
   | WRITE       |  1 | 01     |   A5-A0  | D15-D0  | RDY/BSY  | 25     |
   ----------------------------------------------------------------------
   | WRAL        |  1 | 00     | 01xxxxxx | D15-D0  | RDY/BSY  | 25     |
   ----------------------------------------------------------------------
*/
enum opcodes_93c46 {
    EWDS  = 0x00, WRAL  = 0x10, ERAL  = 0x20, EWEN  = 0x30, // Extended Opcodes
    WRITE = 0x40, READ  = 0x80, ERASE = 0xc0 // Addressed Opcodes
};

void eep93c46_init(eep93c46_t* const eep) {
    eep->clk = 0;
    eep->cs = 0;
    eep->cyc = 0;
    eep->dataout = 0x01;
    eep->opcode = 0;
    eep->addr = 0x00;
    eep->mode = EEP93C46_MODE_START;
    eep->wrenable = 0;
    eep->datain = 0x0000;
}

uint8_t eep93c46_rd(eep93c46_t* const eep) {
    // Return the pin status of CS, CLK, and DO
    return eep->cs | 0x02 | eep->dataout; // CLK is always returned high
}

void eep93c46_wr(eep93c46_t* const eep, uint8_t *mem, uint8_t data) {
    /* CS high selects the device. CS low deselects the device and forces it
       into standby mode.
    */
    if(!(data & 0x04)) { // CS is low
        if (eep->cs) // CS is going high to low, wait for START bit
            eep->mode = EEP93C46_MODE_START;

        eep->cyc = 0;
        eep->cs = data & 0x04;
        eep->clk = data & 0x02;
        eep->dataout = 0x01;
        return;
    }

    // Check if CLK is going low to high, and record the CLK and CS pin states
    int clk_lowhigh = !eep->clk && (data & 0x02);
    eep->clk = data & 0x02;
    eep->cs = data & 0x04;

    // All operations are done when CLK goes from low to high
    if (clk_lowhigh) {
        /* The START bit is detected the first time CS and DI are both high
           with respect to the positive edge of CLK. This is the first of 9
           cycles, with the remaining 8 being the opcode and address. Another
           16 cycles will be used for some instructions.
        */
        if (eep->mode == EEP93C46_MODE_START && (data & 0x01)) {
            eep->opcode = 0; // Blank the opcode
            eep->mode = EEP93C46_MODE_OPCODE; // Opcode read
        }
        else if (eep->mode == EEP93C46_MODE_OPCODE) {
            /* 8 bits are shifted in serially to create the Opcode/Address.
               If this opcode does not use the address bits, they still must
               be clocked in.
            */
            eep->opcode = (eep->opcode << 1) | (data & 0x01);

            // Decode Opcode and Address after 8 bits have been shifted in
            if (++eep->cyc < 8)
                return;

            // Reset cycle counter
            eep->cyc = 0;

            /* Address field used for some opcodes -- since there are 0x80
               bytes, accessed two at a time (words), the address can be a
               maximum of 0x7e.
            */
            eep->addr = (eep->opcode & 0x3f) << 1;

            // Decode the opcode and set the mode for the next write
            switch (eep->opcode & 0xc0) {
                case 0: { // Extended Opcodes
                    switch (eep->opcode & 0x30) {
                        case EWDS: { // Erase/Write Disable
                            eep->wrenable = 0;
                            eep->mode = EEP93C46_MODE_STANDBY;
                            break;
                        }
                        case WRAL: { // Write All
                            eep->datain = 0x0000;
                            eep->mode = EEP93C46_MODE_WRAL;
                            break;
                        }
                        case ERAL: { // Erase All
                            if (eep->wrenable) {
                                for (int i = 0; i < 0x80; ++i)
                                    mem[i] = 0xff;
                            }
                            eep->mode = EEP93C46_MODE_STANDBY;
                            eep->dataout = 0x01; // BSY
                            break;
                        }
                        case EWEN: { // Erase/Write Enable
                            eep->wrenable = 1;
                            eep->mode = EEP93C46_MODE_STANDBY;
                            break;
                        }
                    }
                    break;
                }
                case WRITE: { // Write
                    eep->datain = 0x0000;
                    eep->mode = EEP93C46_MODE_WRITE;
                    break;
                }
                case READ: { // Read
                    eep->datain =
                        mem[eep->addr] | (mem[eep->addr + 1] << 8);
                    eep->mode = EEP93C46_MODE_READ;
                    eep->dataout = 0x00;
                    break;
                }
                case ERASE: { // Erase
                    if (eep->wrenable)
                        mem[eep->addr] = mem[eep->addr + 1] = 0xff;
                    eep->mode = EEP93C46_MODE_STANDBY;
                    eep->dataout = 0x01; // BSY
                    break;
                }
            }
        }
        else if (eep->mode == EEP93C46_MODE_WRAL) { // Write All
            // Shift 16 bits in and then fill the entire 64 words with the data
            eep->datain = (eep->datain << 1) | (data & 0x01);

            if (++eep->cyc < 16)
                return;

            if (eep->wrenable) {
                for (int i = 0; i < 0x80;) { // 128 bytes == 64 words
                    mem[i++] = eep->datain & 0xff;
                    mem[i++] = eep->datain >> 8;
                }
            }
            eep->mode = EEP93C46_MODE_STANDBY;
            eep->dataout = 0x01; // BSY
        }
        else if (eep->mode == EEP93C46_MODE_WRITE) { // Write
            // Shift 16 bits in and then write to an address
            eep->datain = (eep->datain << 1) | (data & 0x01);

            if (++eep->cyc < 16)
                return;

            if (eep->wrenable) {
                mem[eep->addr] = eep->datain & 0xff;
                mem[eep->addr + 1] = eep->datain >> 8;
            }
            eep->mode = EEP93C46_MODE_STANDBY;
            eep->dataout = 0x01; // BSY
        }
        else if (eep->mode == EEP93C46_MODE_READ) { // Read
            // Shift each of the 16 bits out serially
            eep->dataout = ((eep->datain >> (15 - eep->cyc)) & 0x01);

            if (++eep->cyc < 16)
                return;

            // Increment the address to read the next 16-bit value
            eep->addr = (eep->addr + 2) & 0x7e;
            eep->datain = mem[eep->addr] | (mem[eep->addr + 1] << 8);
        }
    }
}
