WD1770.java

/*
 * wd1770.c - WD1770/1772 emulation for the 1571 and 1581 disk drives.
 *
 * Rewritten by
 *  Kajtar Zsolt <soci@c64.rulez.org>
 *
 * 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.
 *
 */

package libsidplay.components.c1541;

import java.io.File;
import java.io.IOException;
import java.util.function.LongSupplier;

/**
 * WD1770/1772 microcode, ported from VICE d928b850b7ef4c1b1826a6efd175d8eaa80344d8.
 * Register accesses advance the controller to the drive CPU clock; no host-time polling.
 * <p>
 * Keep the identifiers, expressions and state-machine layout aligned with VICE's
 * {@code src/drive/iec/wd1770.c} so later upstream changes can be compared directly.
 * Register write gates and forced-interrupt acknowledgement follow the original
 * WD177X-00 data sheet, including corrections to the inherited microcode.
 */
public final class WD1770 implements DriveController {
    /**
     * Status register address (read).
     */
    private static final int WD_STATUS = 0;
    /**
     * Command register address (write).
     */
    private static final int WD_COMMAND = 0;
    /**
     * Track register address.
     */
    private static final int WD_TRACK = 1;
    /**
     * Sector register address.
     */
    private static final int WD_SECTOR = 2;
    /**
     * Data register address.
     */
    private static final int WD_DATA = 3;
    /**
     * Write-sector deleted-data address mark selection.
     */
    private static final int WD_A = 0x01;
    /**
     * Type I command step-rate selection mask.
     */
    private static final int WD_R = 0x03;
    /**
     * Type I command verify flag.
     */
    private static final int WD_V = 0x04;
    /**
     * Type II/III command head-settling delay flag.
     */
    private static final int WD_E = 0x04;
    /**
     * Command flag that skips the motor spin-up delay.
     */
    private static final int WD_H = 0x08;
    /**
     * Step-command track-register update flag.
     */
    private static final int WD_U = 0x10;
    /**
     * Type II command multiple-sector flag.
     */
    private static final int WD_M = 0x10;
    /**
     * Force-interrupt flag for index pulses.
     */
    private static final int WD_I2 = 0x04;
    /**
     * Force-interrupt flag for an immediate interrupt.
     */
    private static final int WD_I3 = 0x08;
    /**
     * Status: motor on.
     */
    private static final int WD_MO = 0x80;
    /**
     * Status: write protected.
     */
    private static final int WD_WP = 0x40;
    /**
     * Status: deleted-data record type.
     */
    private static final int WD_RT = 0x20;
    /**
     * Type I status: seek error.
     */
    private static final int WD_SE = 0x10;
    /**
     * Type II/III status: record not found.
     */
    private static final int WD_RNF = 0x10;
    /**
     * Status: CRC error.
     */
    private static final int WD_CRC = 0x08;
    /**
     * Type I status: head at track zero.
     */
    private static final int WD_T0 = 0x04;
    /**
     * Type II/III status: lost data.
     */
    private static final int WD_LD = 0x04;
    /**
     * Type I status: index pulse.
     */
    private static final int WD_IP = 0x02;
    /**
     * Type II/III status: data request.
     */
    private static final int WD_DRQ = 0x02;
    /**
     * Status: command in progress.
     */
    private static final int WD_BSY = 0x01;
    /**
     * Restore command opcode.
     */
    private static final int WD_RESTORE = 0x00;
    /**
     * Step command opcode.
     */
    private static final int WD_STEP = 0x20;
    /**
     * Step-in command opcode.
     */
    private static final int WD_STEP_IN = 0x40;
    /**
     * Step-out command opcode.
     */
    private static final int WD_STEP_OUT = 0x60;
    /**
     * Write-sector command opcode.
     */
    private static final int WD_WRITE_SECTOR = 0xa0;
    /**
     * Read-track command opcode.
     */
    private static final int WD_READ_TRACK = 0xe0;
    /**
     * Write-track command opcode.
     */
    private static final int WD_WRITE_TRACK = 0xf0;
    /**
     * Step delays in microseconds, indexed by WD1770/1772 variant and command rate bits.
     */
    private static final int[][] STEP_RATES = {{6000, 12000, 20000, 30000}, {6000, 12000, 2000, 3000}};
    /**
     * Command decoding masks, in the same order as COMMANDS and TYPES.
     */
    private static final int[] MASKS = {0xf0,0xf0,0xe0,0xe0,0xe0,0xe0,0xe0,0xf0,0xf0,0xf0,0xf0};
    /**
     * Command opcodes in VICE decoding order.
     */
    private static final int[] COMMANDS = {0,0x10,0x20,0x40,0x60,0x80,0xa0,0xc0,0xe0,0xd0,0xf0};
    /**
     * Microcode type selected by each command decoding entry.
     */
    private static final int[] TYPES = {1,1,1,1,1,2,2,3,3,4,3};
    /**
     * Current drive CPU clock in scheduler cycles.
     */
    private final LongSupplier clock;
    /**
     * Rotating MFM surface and head mechanics.
     */
    private final MFMTrack fdd = new MFMTrack();
    /**
     * Step-rate table selection: 0 for WD1770, 1 for WD1772.
     */
    private final int is1772;
    /**
     * Number of drive scheduler cycles per microsecond.
     */
    private final int clock_frequency = 2;
    /**
     * Registers and microcode state, retaining the corresponding VICE identifiers.
     */
    private int data, track, sector, status, cmd, crc, command, type, step, byte_count, direction;
    /**
     * Microcode scratch value for index counts, timing and sector size.
     */
    private long tmp;
    /**
     * Interrupt, density and synchronization state in VICE representation.
     * The density input stays at its default value of 0 for the MFM surface supported here.
     */
    private int irq, dden, sync;
    /** Immediate forced IRQ needs D0 before ordinary acknowledgements can clear it. */
    private boolean immediateIrq;
    /**
     * Drive scheduler cycle reached by the controller microcode.
     */
    private long clk;
    /**
     * Activity LED state controlled by the drive electronics.
     */
    private boolean led;
    /**
     * Mounted image file name, or null when the drive is empty.
     */
    private String diskName;

    /**
     * Create an MFM controller driven by the drive CPU clock.
     *
     * @param clock  current scheduler cycle at 2 MHz
     * @param wd1772 true to use WD1772 step rates
     */
    public WD1770(LongSupplier clock, boolean wd1772) {
        this.clock = clock;
        is1772 = wd1772 ? 1 : 0;
        reset();
    }
    /**
     * Get the command preparation delay.
     *
     * @return delay in drive scheduler cycles
     */
    private int prepare() { return clock_frequency * 24; }
    /**
     * Get the duration of one MFM byte cell.
     *
     * @return drive scheduler cycles per byte cell
     */
    private int byteRate() { return clock_frequency * 32; }
    /**
     * Get the selected head-step delay.
     *
     * @return delay in drive scheduler cycles
     */
    private int stepRate() { return clock_frequency * STEP_RATES[is1772][cmd & WD_R]; }
    /**
     * Get the head-settling delay.
     *
     * @return delay in drive scheduler cycles
     */
    private int settling() { return clock_frequency * 30000; }
    /**
     * Reset controller registers and microcode while retaining the mounted surface and its protection.
     */
    public void reset() {
        type = status = track = sector = data = cmd = irq = sync = 0;
        immediateIrq = false;
        step = -1;
        clk = clock.getAsLong();
    }
    /**
     * Advance to the drive CPU clock, then write a controller register.
     *
     * @param address register address; only the low two bits are decoded
     * @param value   register value
     */
    public void write(int address, byte value) {
        execute();
        int b = value & 255;
        switch (address & 3) {
            case WD_COMMAND:
                // Only a Force Interrupt command can replace an executing command.
                if ((status & WD_BSY) != 0 && (b & 0xf0) != 0xd0) break;
                acknowledgeIRQ();
                cmd = b;
                for (int i = 0; i < COMMANDS.length; i++) {
                    if ((b & MASKS[i]) == COMMANDS[i]) {
                        command = COMMANDS[i]; type = TYPES[i]; break;
                    }
                }
                clk += fdd.rotate((clock.getAsLong() - clk) / byteRate()) * byteRate();
                step = 0;
                execute();
                break;
            case WD_TRACK:
                if ((status & WD_BSY) == 0) track = b;
                break;
            case WD_SECTOR:
                if ((status & WD_BSY) == 0) sector = b;
                break;
            case WD_DATA: status &= ~WD_DRQ; data = b; break;
            default: break;
        }
    }
    /**
     * Advance to the drive CPU clock, then read a controller register.
     * Reading status acknowledges ordinary IRQ; D8 first needs D0.
     * Reading data acknowledges DRQ.
     *
     * @param address register address; only the low two bits are decoded
     * @return register value
     */
    public byte read(int address) {
        execute();
        switch (address & 3) {
            case WD_STATUS: acknowledgeIRQ(); return (byte) status;
            case WD_TRACK: return (byte) track;
            case WD_SECTOR: return (byte) sector;
            case WD_DATA: status &= ~WD_DRQ; return (byte) data;
            default: return 0;
        }
    }
    /** A forced immediate interrupt ignores acknowledgements until D0 enables them. */
    private void acknowledgeIRQ() {
        if (!immediateIrq) irq = 0;
    }
    /**
     * Advance the microcode and read its interrupt request.
     *
     * @return true if IRQ is asserted
     */
    public boolean isIRQ() { execute(); return irq != 0; }
    /**
     * Advance the microcode and select a physical head.
     *
     * @param side head selection (0 or 1)
     */
    public void setSide(int side) { execute(); fdd.selectHead(side); }
    /**
     * Advance the microcode and set the physical motor state.
     *
     * @param on motor on/off
     */
    public void setMotor(boolean on) { execute(); fdd.setMotor(on); }
    /**
     * Set the activity LED state.
     *
     * @param on LED on/off
     */
    public void setLED(boolean on) { led = on; }
    /**
     * Read media write protection.
     *
     * @return true when the disk is protected or the drive is empty
     */
    public boolean isWriteProtected() { return fdd.writeProtect() != 0; }
    /**
     * Read the surface disk-change latch.
     *
     * @return true until a seek acknowledges the inserted disk
     */
    public boolean diskChange() { return fdd.diskChange() != 0; }
    @Override public boolean isLEDOn() { return led; }
    @Override public boolean isMotorOn() { return fdd.isMotorOn(); }
    @Override public int getHalfTrack() { return (fdd.getTrack() + 1) * 2; }
    @Override public int getSide() { return fdd.getHead(); }
    /**
     * Get the mounted image file name.
     *
     * @return image file name, or null when the drive is empty
     */
    public String getDiskName() { return diskName; }
    @Override public DiskImage insertDisk(File file) throws IOException {
        if (DiskImage.detect(file) != DiskImage.Format.D81) throw new IOException("1581 requires D81 media");
        fdd.flush();
        DiskImage next = DiskImage.attach(null, file);
        try { ejectDisk(); } catch (IOException | RuntimeException e) { next.close(); throw e; }
        fdd.attach((D81) next);
        diskName = file.getName();
        return next;
    }
    @Override public void ejectDisk() throws IOException {
        fdd.detach();
        diskName = null;
    }
    /**
     * Write pending MFM surface data to the mounted image.
     *
     * @throws IOException image data could not be written
     */
    public void flush() throws IOException { fdd.flush(); }

    /**
     * Advance the controller microcode to the current drive CPU clock.
     * The upstream switch layout is retained, with documented forced-interrupt corrections.
     */
    @SuppressWarnings("fallthrough")
    private void execute() {
    int res;

    while (true) {
        switch (type) {
            case -1:
                status &= ~(WD_WP | WD_IP | WD_T0);
                status |= (fdd.index() != 0) ? WD_IP : 0;
                status |= (fdd.track0() != 0) ? WD_T0 : 0;
                status |= (fdd.writeProtect() != 0) ? WD_WP : 0;
                /* fall through */
            case 0: /* idle */
                if ((clock.getAsLong() < clk + prepare())) {
                    return;
                }
                status &= ~WD_BSY;
                clk += fdd.rotate((clock.getAsLong() - clk) / byteRate()) * byteRate();
                if ((fdd.indexCount() >= 10)) {
                    status &= ~WD_MO;
                }
                if (((cmd & WD_I2) != 0 && (fdd.indexCount() != tmp))) {
                    irq = 1;
                    tmp = fdd.indexCount();
                }
                return;
            case 1: /* type 1 */
                switch (step) {
                    case 0:
                        if ((clock.getAsLong() < clk + prepare())) {
                            return;
                        }
                        clk += prepare();
                        status |= WD_BSY;
                        status &= ~(WD_CRC | WD_SE | WD_DRQ);
                        acknowledgeIRQ();
                        step++;
                        /* fall through */
                    case 1:
                        if (((cmd & WD_H) != 0 || (status & WD_MO) != 0)) {
                            status |= WD_MO;
                            step += 2;
                            continue;
                        }
                        status |= WD_MO;
                        fdd.resetIndexCount();
                        step++;
                        /* fall through */
                    case 2:
                        clk += fdd.rotate((clock.getAsLong() - clk) / byteRate()) * byteRate();
                        if ((fdd.indexCount() < 6)) {
                            return;
                        }
                        step++;
                        /* fall through */
                    case 3:
                        switch (command) {
                            case WD_STEP:
                                break;
                            case WD_STEP_IN:
                                direction = 1;
                                break;
                            case WD_STEP_OUT:
                                direction = 0;
                                break;
                            case WD_RESTORE:
                                track = 0xff;
                                data = 0x00;
                                /* fall through */
                            default:
                                step++;
                                continue;
                        }
                        step = ((cmd & WD_U) != 0) ? 5 : 6;
                        continue;
                    case 4:
                        if ((data == track)) {
                            step = 8;
                            continue;
                        }
                        direction = data > track ? 1 : 0;
                        step++;
                        /* fall through */
                    case 5:
                        track = (track + (direction != 0 ? 1 : -1)) & 255;
                        step++;
                        /* fall through */
                    case 6:
                        if (((fdd.track0()) != 0 && !((direction) != 0))) {
                            track = 0;
                            step = 8;
                            continue;
                        }
                        fdd.seek(direction);
                        step++;
                        /* fall through */
                    case 7:
                        if ((clock.getAsLong() < clk + stepRate())) {
                            return;
                        }
                        clk += stepRate();
                        if ((cmd < WD_STEP)) {
                            step = 4;
                            continue;
                        }
                        step++;
                        /* fall through */
                    case 8:
                        if (!((cmd & WD_V) != 0)) {
                            type = -1;
                            break;
                        }
                        step++;
                        /* fall through */
                    case 9:
                        if ((clock.getAsLong() < clk + settling())) {
                            return;
                        }
                        clk += settling();
                        fdd.resetIndexCount();
                        sync = 0;
                        step++;
                        /* fall through */
                    case 10:
                        if ((fdd.indexCount() >= 6)) {
                            status |= WD_SE;
                            type = -1;
                            break;
                        }
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        res = fdd.read();
                        if ((!((dden) != 0) || (res != 0x1fe))) {
                            if ((!((sync) != 0) || (res != 0xfe))) {
                                sync = res == 0x1a1 ? 1 : 0;
                                continue;
                            }
                        }
                        sync = 0;
                        crc = 0xb230;
                        byte_count = 6;
                        step++;
                        /* fall through */
                    case 11:
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        res = fdd.read();
                        if (((byte_count == 6) && (res != track))) {
                            step--;
                            continue;
                        }
                        crc = MFMTrack.crc(crc, res);
                        if ((--byte_count) != 0) {
                            continue;
                        }
                        if ((crc) != 0) {
                            status |= WD_CRC;
                            step--;
                            continue;
                        }
                        status &= ~WD_CRC;
                        type = -1;
                        break;
                }
                break;
            case 2: /* type 2 */
                switch (step) {
                    case 0:
                        if ((clock.getAsLong() < clk + prepare())) {
                            return;
                        }
                        clk += prepare();
                        status |= WD_BSY;
                        status &= ~(WD_DRQ | WD_LD | WD_RNF | WD_RT | WD_WP);
                        step++;
                        /* fall through */
                    case 1:
                        if (((cmd & WD_H) != 0 || (status & WD_MO) != 0)) {
                            status |= WD_MO;
                            step += 2;
                            continue;
                        }
                        status |= WD_MO;
                        fdd.resetIndexCount();
                        step++;
                        /* fall through */
                    case 2:
                        clk += fdd.rotate((clock.getAsLong() - clk) / byteRate()) * byteRate();
                        if ((fdd.indexCount() < 6)) {
                            return;
                        }
                        step++;
                        /* fall through */
                    case 3:
                        if (!((cmd & WD_E) != 0)) {
                            step += 2;
                            continue;
                        }
                        step++;
                        /* fall through */
                    case 4:
                        if ((clock.getAsLong() < clk + settling())) {
                            return;
                        }
                        clk += settling();
                        step++;
                        /* fall through */
                    case 5:
                        if (((command == WD_WRITE_SECTOR) && (fdd.writeProtect()) != 0)) {
                            status |= WD_WP;
                            type = 0;
                            break;
                        }
                        fdd.resetIndexCount();
                        sync = 0;
                        step++;
                        /* fall through */
                    case 6:
                        if ((fdd.indexCount() >= 5)) {
                            status |= WD_RNF;
                            type = 0;
                            break;
                        }
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        res = fdd.read();
                        if ((!((dden) != 0) || (res != 0x1fe))) {
                            if ((!((sync) != 0) || (res != 0xfe))) {
                                sync = res == 0x1a1 ? 1 : 0;
                                continue;
                            }
                        }
                        sync = 0;
                        crc = 0xb230;
                        byte_count = 6;
                        step++;
                        /* fall through */
                    case 7:
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        res = fdd.read();
                        if (((byte_count == 6) && (res != track))) {
                            step--;
                            continue;
                        }
                        if (((byte_count == 4) && (res != sector))) {
                            step--;
                            continue;
                        }
                        if ((byte_count == 3)) {
                            tmp = res;
                        }
                        crc = MFMTrack.crc(crc, res);
                        if ((--byte_count) != 0) {
                            continue;
                        }
                        if ((crc) != 0) {
                            status |= WD_CRC;
                            step--;
                            continue;
                        }
                        status &= ~WD_CRC;
                        crc = 0xffff;
                        if ((command == WD_WRITE_SECTOR)) {
                            byte_count = 0;
                            step = 10;
                            continue;
                        }
                        byte_count = 43;
                        step++;
                        /* fall through */
                    case 8:
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        if (!((byte_count--) != 0)) {
                            step -= 2;
                            continue;
                        }
                        clk += byteRate();
                        res = fdd.read();
                        if ((!((dden) != 0) || ((res != 0x1fb) && (res != 0x1f8)))) {
                            if ((!((sync) != 0) || ((res != 0xfb) && (res != 0xf8)))) {
                                if (!((sync) != 0)) {
                                    crc = 0xffff;
                                }
                                crc = MFMTrack.crc(crc, res);
                                sync = res == 0x1a1 ? 1 : 0;
                                continue;
                            }
                        }
                        crc = MFMTrack.crc(crc, res);
                        status |= ((res & 0xff) == 0xf8) ? WD_RT : 0;
                        byte_count = (128 << tmp) + 2;
                        step++;
                        /* fall through */
                    case 9:
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        res = fdd.read();
                        if ((byte_count > 2)) {
                            status |= ((status & WD_DRQ) != 0) ? WD_LD : WD_DRQ;
                            data = res & 255;
                        }
                        crc = MFMTrack.crc(crc, res);
                        if ((--byte_count) != 0) {
                            continue;
                        }
                        if ((crc) != 0) {
                            status |= WD_CRC;
                            type = 0;
                            break;
                        }
                        if ((cmd & WD_M) != 0) {
                            sector++;
                            step = 5;
                            continue;
                        }
                        type = 0;
                        break;
                    case 10:
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        byte_count++;
                        status |= (byte_count == 2) ? WD_DRQ : 0;
                        if (((byte_count == (2 + 9)) && (status & WD_DRQ) != 0)) {
                            status ^= WD_DRQ | WD_LD;
                            type = 0;
                            break;
                        }
                        if ((byte_count <= ((dden != 0) ? 0 : 11) + 2 + 9)) {
                            fdd.read();
                            continue;
                        }
                        if ((byte_count <= ((dden != 0) ? 6 : (11 + 12)) + 2 + 9)) {
                            fdd.write(0);
                            continue;
                        }
                        if ((!((dden) != 0) && (byte_count <= (11 + 12 + 2 + 9 + 3)))) {
                            fdd.write(0x1a1);
                            crc = MFMTrack.crc(crc, 0xa1);
                            continue;
                        }
                        res = (((cmd & WD_A) != 0) ? 0xf8 : 0xfb) | ((dden != 0) ? 0x100 : 0);
                        fdd.write(res);
                        crc = MFMTrack.crc(crc, res);
                        byte_count = (128 << tmp) + 3;
                        step++;
                        /* fall through */
                    case 11:
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        switch (--byte_count) {
                            case 0:
                                fdd.write(0xff);
                                break;
                            case 1:
                                fdd.write(crc & 0xff);
                                continue;
                            case 2:
                                fdd.write(crc >> 8);
                                continue;
                            default:
                                status |= ((status & WD_DRQ) != 0) ? WD_LD : WD_DRQ;
                                crc = MFMTrack.crc(crc, data);
                                fdd.write(data);
                                data = 0;
                                continue;
                        }
                        if ((cmd & WD_M) != 0) {
                            sector++;
                            step = 5;
                            continue;
                        }
                        type = 0;
                        break;
                }
                break;
            case 3: /* type 3 */
                switch (step) {
                    case 0:
                        if ((clock.getAsLong() < clk + prepare())) {
                            return;
                        }
                        clk += prepare();
                        status |= WD_BSY;
                        status &= ~(WD_DRQ | WD_LD | WD_RNF | WD_CRC);
                        step++;
                        /* fall through */
                    case 1:
                        if (((cmd & WD_H) != 0 || (status & WD_MO) != 0)) {
                            status |= WD_MO;
                            step += 2;
                            continue;
                        }
                        status |= WD_MO;
                        fdd.resetIndexCount();
                        step++;
                        /* fall through */
                    case 2:
                        clk += fdd.rotate((clock.getAsLong() - clk) / byteRate()) * byteRate();
                        if ((fdd.indexCount() < 6)) {
                            return;
                        }
                        step++;
                        /* fall through */
                    case 3:
                        if (!((cmd & WD_E) != 0)) {
                            step += 2;
                            continue;
                        }
                        step++;
                        /* fall through */
                    case 4:
                        if ((clock.getAsLong() < clk + settling())) {
                            return;
                        }
                        clk += settling();
                        step++;
                        /* fall through */
                    case 5:
                        fdd.resetIndexCount();
                        sync = 0;
                        step++;
                        if ((command == WD_WRITE_TRACK)) {
                            if ((fdd.writeProtect()) != 0) {
                                status |= WD_WP;
                                type = 0;
                                break;
                            }
                            status |= WD_DRQ;
                            byte_count = 3;
                            step = 9;
                            continue;
                        }
                        if ((command != WD_READ_TRACK)) {
                            step++;
                            continue;
                        }
                        /* fall through */
                    case 6:
                        if ((fdd.indexCount() < 1)) {
                            clk += fdd.rotate((clock.getAsLong() - clk) / byteRate()) * byteRate();
                            return;
                        }
                        if ((fdd.indexCount() > 1)) {
                            type = 0;
                            break;
                        }
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        data = fdd.read() & 255;
                        status |= ((status & WD_DRQ) != 0) ? WD_LD : WD_DRQ;
                        continue;
                    case 7:
                        if ((fdd.indexCount() >= 6)) {
                            status |= WD_RNF;
                            type = 0;
                            break;
                        }
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        res = fdd.read();
                        if ((!((dden) != 0) || (res != 0x1fe))) {
                            if ((!((sync) != 0) || (res != 0xfe))) {
                                sync = res == 0x1a1 ? 1 : 0;
                                continue;
                            }
                        }
                        crc = 0xb230;
                        byte_count = 6;
                        step++;
                        /* fall through */
                    case 8:
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        status |= ((status & WD_DRQ) != 0) ? WD_LD : WD_DRQ;
                        clk += byteRate();
                        data = fdd.read() & 255;
                        if ((byte_count == 6)) {
                            sector = data;
                        }
                        crc = MFMTrack.crc(crc, data);
                        if ((--byte_count) != 0) {
                            continue;
                        }
                        status |= (crc != 0) ? WD_CRC : 0;
                        type = 0;
                        break;
                    case 9:
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        fdd.read();
                        if ((--byte_count) != 0) {
                            continue;
                        }
                        if ((status & WD_DRQ) != 0) {
                            status ^= WD_DRQ | WD_LD;
                            type = 0;
                            break;
                        }
                        byte_count = 0;
                        tmp = 0;
                        step++;
                        /* fall through */
                    case 10:
                        if ((fdd.indexCount() < 1)) {
                            clk += fdd.rotate((clock.getAsLong() - clk) / byteRate()) * byteRate();
                            return;
                        }
                        if ((fdd.indexCount() > 1)) {
                            status &= ~WD_DRQ;
                            type = 0;
                            break;
                        }
                        if ((clock.getAsLong() < clk + byteRate())) {
                            return;
                        }
                        clk += byteRate();
                        res = data;
                        if ((byte_count) != 0) {
                            fdd.write(crc & 0xff);
                            byte_count--;
                        } else {
                            status |= ((status & WD_DRQ) != 0) ? WD_LD : WD_DRQ;

                            if ((dden) != 0) {
                                switch (res) {
                                    case 0xf7:
                                        byte_count = 1;
                                        res = crc >> 8;
                                        tmp = 0;
                                        break;
                                    case 0xf8:
                                    case 0xf9:
                                    case 0xfa:
                                    case 0xfb:
                                    case 0xfe:
                                        if (!((tmp) != 0)) {
                                            crc = 0xffff;
                                            tmp = 1;
                                        }
                                        /* fall through */
                                    case 0xfc:
                                        res |= 0x100;
                                }
                            } else {
                                switch (res) {
                                    case 0xf5:
                                        res = 0x1a1;
                                        if (!((tmp) != 0)) {
                                            crc = 0xffff;
                                            tmp = 1;
                                        }
                                        break;
                                    case 0xf6:
                                        res = 0x1c2;
                                        break;
                                    case 0xf7:
                                        byte_count = 1;
                                        res = crc >> 8;
                                        tmp = 0;
                                        break;
                                }
                            }
                            if ((tmp) != 0) {
                                crc = MFMTrack.crc(crc, res);
                            }
                            fdd.write(res);
                            data = 0;
                        }
                        continue;
                }
                break;
            case 4: { /* type 4 */
                if ((clock.getAsLong() < clk + prepare())) {
                    return;
                }
                clk += prepare();
                final boolean wasBusy = (status & WD_BSY) != 0;
                // Aborting preserves the old command's flags; idle Force Interrupt selects Type I status.
                status &= wasBusy ? ~WD_BSY : WD_MO;
                if ((cmd & WD_I3) != 0) {
                    immediateIrq = true;
                    irq = 1;
                } else if (cmd == 0xd0) {
                    immediateIrq = false;
                }
                fdd.resetIndexCount();
                tmp = fdd.indexCount();
                type = wasBusy ? 0 : -1;
                continue;
            }
        }
        cmd = 0;
        irq = 1;
        fdd.resetIndexCount();
    }

    }
}