NIB.java

package libsidplay.components.c1541;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NIB extends G64 {
    @Override public Format getFormat() { return Format.NIB; }

    private static class TrackCycle {
        public TrackCycle(final int start, final int stop) {
            cycleStart = start;
            cycleStop = stop;
        }

        /**
         * start position of cycle
         */
        int cycleStart;
        /**
         * stop position of the cycle
         */
        int cycleStop;
    }

    /**
     * Expected raw NIB image header.
     */
    static final String IMAGE_HEADER = "MNIB-1541-RAW";

    /**
     * NIB file track data length.
     */
    private static final int MNIB_TRACK_LENGTH = 0x2000;

    private static final int MATCH_LENGTH = 7;
    private static final int MIN_TRACK_LENGTH = 0x1780;
    private static final int MAX_NIB_SIZE = 256 + MAX_TRACKS_1541 * 2 * MNIB_TRACK_LENGTH;
    static final int MAX_NB2_SIZE = 256 + MAX_TRACKS_1541 * 2 * 16 * MNIB_TRACK_LENGTH;

    /**
     * NIB file header.
     */
    private final byte[] nibHeader = new byte[0x100];
    /** Odd captures have their own buffers; the regular banks retain both D71 surfaces. */
    private byte[][] halfTrackData = new byte[MAX_TRACKS_1541][];
    private int[] halfTrackSize = new int[MAX_TRACKS_1541];
    private byte[][][] trackCycles = new byte[MAX_TRACKS_1541 * 2 + 2][][];
    /** Last published decoded container; untouched records and acquisition alternatives retain their bytes. */
    private byte[] sourceImage;
    private final boolean[] pendingNibWrites = new boolean[MAX_TRACKS_1541 * 2];
    private final IOException[] nibRecordingErrors = new IOException[MAX_TRACKS_1541 * 2];
    private final byte[][] recordedNibSpeeds = new byte[MAX_TRACKS_1541 * 2][];
    private int selectedNibHalfTrack = 2;

    /** Quality: 3=complete overlap, 2=SYNC heuristic, 1=flagged signal, 0=blank policy. */
    private record Surface(byte[] data, int length, int quality, byte[] capture) { }

    /**
     * Constructor.
     *
     * @param gcr      GCR support
     * @param fileName disk image file name
     * @param fd       file handle of the disk image
     * @param readOnly mount read-only?
     */
    public NIB(final GCR gcr, final String fileName, final RandomAccessFile fd, final boolean readOnly) {
        super(gcr, fileName, fd, readOnly);
    }

    /**
     * Map each header entry to its surface before extracting a revolution.
     *
     * @throws IOException disk image file could not be attached
     */
    @Override
    protected void attach() throws IOException {
        byte[] imageData = readImageData();
        if (imageData.length < nibHeader.length) throw new IOException("Truncated NIB header");
        byte[] header = Arrays.copyOf(imageData, nibHeader.length);
        if (!new String(header, StandardCharsets.ISO_8859_1).startsWith(IMAGE_HEADER)) {
            throw new IOException("GCR image is not MNIB-1541-RAW format.");
        }
        // NIBTools read_nib/write_nib pair header IDs with sequential 8 KiB
        // captures. Holes in track numbering do not occupy file records.
        byte[][] surfaces = new byte[MAX_TRACKS_1541][GCR.NUM_MAX_BYTES_TRACK];
        int[] lengths = new int[MAX_TRACKS_1541];
        byte[][] halfSurfaces = new byte[MAX_TRACKS_1541][];
        int[] halfLengths = new int[MAX_TRACKS_1541];
        byte[][][] cycles = new byte[MAX_TRACKS_1541 * 2 + 2][][];
        boolean multiplePasses = header[13] == 2;
        int recordSize = MNIB_TRACK_LENGTH * (multiplePasses ? 16 : 1);
        if (imageData.length > (multiplePasses ? MAX_NB2_SIZE : MAX_NIB_SIZE)) throw new IOException("Oversized NIB image");
        for (int track = 0; track < MAX_TRACKS_1541; track++) {
            lengths[track] = RAW_TRACK_SIZE[SPEED_MAP_1541[track]];
            Arrays.fill(surfaces[track], (byte) 0x55);
            surfaces[track][0] = (byte) 0xff;
        }
        boolean[] seen = new boolean[MAX_TRACKS_1541 * 2 + 2];
        long fileLength = imageData.length;
        for (int entry = 16; entry < nibHeader.length; entry += 2) {
            int halfTrack = header[entry] & 0xff;
            if (halfTrack == 0) break;
            if (halfTrack < 2 || halfTrack >= seen.length || seen[halfTrack]) {
                throw new IOException("Invalid or duplicate NIB half-track ID: " + halfTrack);
            }
            seen[halfTrack] = true;
            long offset = 256L + ((entry - 16) / 2L) * recordSize;
            if (offset > fileLength - recordSize) {
                throw new IOException("Truncated NIB capture for half-track " + halfTrack);
            }
            int track = halfTrack / 2 - 1;
            int flags = header[entry + 1] & 255;
            Surface[] passes = new Surface[multiplePasses ? 4 : 1];
            Surface best = null;
            for (int pass = 0; pass < passes.length; pass++) {
                int start = (int) offset + (multiplePasses ? (flags & 3) * 4 + pass : 0) * MNIB_TRACK_LENGTH;
                byte[] capture = Arrays.copyOfRange(imageData, start, start + MNIB_TRACK_LENGTH);
                passes[pass] = extractSurface(capture, flags, track);
                if (best == null || passes[pass].quality > best.quality) best = passes[pass];
            }
            if (multiplePasses) cycles[halfTrack] = alignPasses(best, passes);
            if ((halfTrack & 1) != 0) {
                halfLengths[track] = best.length;
                halfSurfaces[track] = best.data;
            } else {
                lengths[track] = best.length;
                surfaces[track] = best.data;
            }
        }
        // Publish only after every declared record has been checked. Always
        // advance by the surface capacity, including missing/blank tracks.
        for (int track = 0; track < MAX_TRACKS_1541; track++) {
            gcr.setTrackData(surfaces[track], track * GCR.NUM_MAX_BYTES_TRACK, GCR.NUM_MAX_BYTES_TRACK);
            trackSize[track] = lengths[track];
        }
        halfTrackData = halfSurfaces;
        halfTrackSize = halfLengths;
        trackCycles = cycles;
        sourceImage = imageData;
        System.arraycopy(header, 0, nibHeader, 0, header.length);
        Arrays.fill(pendingNibWrites, false);
        Arrays.fill(nibRecordingErrors, null);
        Arrays.fill(recordedNibSpeeds, null);
        tracks = MAX_TRACKS_1541;
    }

    protected byte[] readImageData() throws IOException {
        int limit = getFormat() == Format.NB2 ? MAX_NB2_SIZE : MAX_NIB_SIZE;
        if (fd.length() > limit) throw new IOException("Oversized NIB image");
        byte[] data = new byte[(int) fd.length()];
        fd.seek(0);
        fd.readFully(data);
        return data;
    }

    /** Only combine equal-length samples with a unique stable anchor and at least 95% agreement. */
    private byte[][] alignPasses(Surface best, Surface[] passes) {
        List<byte[]> aligned = new ArrayList<>();
        aligned.add(best.data);
        if (best.quality < 2) return aligned.toArray(byte[][]::new);
        for (Surface pass : passes) {
            if (pass == best) continue;
            byte[] candidate = pass.data;
            if (pass.quality < 2 && best.quality == 3) {
                // A phase-shifted pass may contain only one SYNC edge. Reuse the
                // period proven by another pass, then require independent alignment.
                candidate = Arrays.copyOf(pass.capture, GCR.NUM_MAX_BYTES_TRACK);
            } else if (pass.quality < 2 || pass.length != best.length) {
                continue;
            }
            int rotation = findAlignment(best.data, candidate, best.length);
            if (rotation < 0) continue;
            byte[] data = new byte[GCR.NUM_MAX_BYTES_TRACK];
            for (int i = 0; i < best.length; i++) {
                data[i] = candidate[(i + rotation) % best.length];
            }
            aligned.add(data);
        }
        return aligned.toArray(byte[][]::new);
    }

    private int findAlignment(byte[] reference, byte[] candidate, int length) {
        for (int start = 0; start + 64 <= length; start += 64) {
            boolean[] seen = new boolean[256];
            int distinct = 0;
            for (int i = 0; i < 64; i++) {
                int value = reference[start + i] & 255;
                if (!seen[value]) distinct++;
                seen[value] = true;
            }
            if (distinct < 7 || uniqueAnchor(reference, reference, start, length) != start) continue;
            int position = uniqueAnchor(reference, candidate, start, length);
            if (position >= 0) {
                int rotation = (position - start + length) % length;
                int different = 0;
                for (int i = 0; i < length; i++) {
                    if (reference[i] != candidate[(i + rotation) % length]) different++;
                }
                if (different <= length / 20) return rotation;
            }
        }
        return -1;
    }

    private int uniqueAnchor(byte[] reference, byte[] candidate, int start, int length) {
        int found = -1;
        for (int position = 0; position < length; position++) {
            int i = 0;
            while (i < 64 && reference[start + i] == candidate[(position + i) % length]) i++;
            if (i == 64) {
                if (found >= 0) return -1;
                found = position;
            }
        }
        return found;
    }

    @Override
    int getHalfTrackSize(int halfTrack, int side) {
        int track = halfTrack / 2 - 1;
        return side == 0 && (halfTrack & 1) != 0 && halfTrackData[track] != null
                ? halfTrackSize[track] : super.getHalfTrackSize(halfTrack, side);
    }

    @Override
    void selectHalfTrack(int halfTrack, int side, int oldSize, int newSize) {
        selectedNibHalfTrack = side == 0 ? halfTrack : -1;
        int track = halfTrack / 2 - 1;
        int cycleId = (halfTrack & 1) != 0 && halfTrackData[track] == null ? halfTrack - 1 : halfTrack;
        if (side == 0 && trackCycles[cycleId] != null) {
            gcr.setTrackCycles(trackCycles[cycleId], oldSize, newSize);
        } else if (side == 0 && (halfTrack & 1) != 0 && halfTrackData[track] != null) {
            gcr.setHalfTrackData(halfTrackData[track], oldSize, newSize);
        } else {
            gcr.setHalfTrack(halfTrack + side * 84, oldSize, newSize);
        }
        if (side == 0 && recordedNibSpeeds[cycleId - 2] != null) {
            byte[] speeds = recordedNibSpeeds[cycleId - 2];
            boolean uniform = true;
            for (byte speed : speeds) uniform &= speed == speeds[0];
            if (!uniform) {
                int[] timing = new int[speeds.length + 1];
                for (int i = 0; i < speeds.length; i++) timing[i + 1] = timing[i] + 8 * (16 - speeds[i]);
                gcr.setTrackTiming(timing);
            }
        }
    }

    @Override
    GCR.Recording beginGCRRecording(int halfTrack, int side, long phase) {
        if (side != 0 || isReadOnly()) return null;
        int slot = halfTrack - 2, source = halfTrack;
        if ((halfTrack & 1) != 0 && halfTrackData[halfTrack / 2 - 1] == null) source--;
        byte[][] samples = trackCycles[source];
        if (samples == null) samples = new byte[][]{surface(slot)};
        byte[] speeds = recordedNibSpeeds[source - 2];
        if (speeds == null) {
            speeds = new byte[getHalfTrackSize(halfTrack, 0)];
            Arrays.fill(speeds, (byte) density(source));
        }
        G64Recording[] recorders = new G64Recording[samples.length];
        byte[][] results = new byte[samples.length][];
        byte[][] zones = new byte[1][];
        String[] error = {null};
        for (int i = 0; i < recorders.length; i++) {
            int pass = i;
            byte[] original = Arrays.copyOf(samples[i], speeds.length);
            recorders[i] = new G64Recording(original, speeds, phase, (bytes, recorded) -> {
                results[pass] = bytes;
                zones[0] = recorded;
            }, message -> error[0] = message);
        }
        return new GCR.Recording() {
            @Override
            public void writeBit(boolean value, int density, long elapsed) {
                for (G64Recording recording : recorders) recording.writeBit(value, density, elapsed);
            }

            @Override
            public void finish(long elapsed) {
                for (G64Recording recording : recorders) recording.finish(elapsed);
                if (error[0] != null) recordingFailed(slot, error[0]);
                else if (results[0] != null) installRecording(slot, results, zones[0]);
            }
        };
    }

    @Override
    void recordingFinished(int slot, byte[] bytes, byte[] speeds) {
        installRecording(slot, new byte[][]{bytes}, speeds);
    }

    private void installRecording(int slot, byte[][] samples, byte[] speeds) {
        int halfTrack = slot + 2, oldSize = getHalfTrackSize(halfTrack, 0), length = samples[0].length;
        byte[][] padded = new byte[samples.length][GCR.NUM_MAX_BYTES_TRACK];
        for (int i = 0; i < samples.length; i++) System.arraycopy(samples[i], 0, padded[i], 0, length);
        if ((slot & 1) == 0) {
            gcr.setTrackData(padded[0], slot / 2 * GCR.NUM_MAX_BYTES_TRACK, GCR.NUM_MAX_BYTES_TRACK);
            trackSize[slot / 2] = length;
        } else {
            halfTrackData[slot / 2] = padded[0];
            halfTrackSize[slot / 2] = length;
        }
        trackCycles[halfTrack] = padded;
        recordedNibSpeeds[slot] = speeds.clone();
        pendingNibWrites[slot] = true;
        nibRecordingErrors[slot] = null;
        if (length < MIN_TRACK_LENGTH) nibRecordingErrors[slot] = new IOException("NIB cannot retain this revolution length: " + length);
        for (byte speed : speeds)
            if (speed != speeds[0]) nibRecordingErrors[slot] = new IOException("NIB captures cannot retain per-byte density changes; use G64");
        if (selectedNibHalfTrack == halfTrack) selectHalfTrack(halfTrack, 0, oldSize, length);
    }

    @Override
    void recordingFailed(int slot, String message) {
        pendingNibWrites[slot] = true;
        nibRecordingErrors[slot] = new IOException(message);
    }

    private int density(int halfTrack) {
        int entry = entry(nibHeader, halfTrack);
        return entry < 0 ? SPEED_MAP_1541[halfTrack / 2 - 1] : nibHeader[entry + 1] & 3;
    }

    private byte[] surface(int slot) {
        int length = getHalfTrackSize(slot + 2, 0);
        return (slot & 1) != 0 && halfTrackData[slot / 2] != null
                ? Arrays.copyOf(halfTrackData[slot / 2], length)
                : gcr.getTrackData(slot / 2 * GCR.NUM_MAX_BYTES_TRACK, length);
    }

    private static int entry(byte[] header, int halfTrack) {
        for (int i = 16; i < 256 && header[i] != 0; i += 2)
            if ((header[i] & 255) == halfTrack) return i;
        return -1;
    }

    @Override
    boolean hasPendingGCRWrites() {
        for (boolean pending : pendingNibWrites) if (pending) return true;
        return false;
    }

    @Override
    void flushPendingGCRWrites() throws IOException {
        if (!hasPendingGCRWrites()) return;
        if (isReadOnly()) throw new IOException("Disk is write protected");
        for (IOException error : nibRecordingErrors) if (error != null) throw error;
        byte[] candidate = sourceImage.clone();
        int recordSize = MNIB_TRACK_LENGTH * (nibHeader[13] == 2 ? 16 : 1), count = 0, recordedTracks = MIN_TRACKS_1541;
        while (count < MAX_TRACKS_1541 * 2 && candidate[16 + count * 2] != 0) {
            recordedTracks = Math.max(recordedTracks, (candidate[16 + count * 2] & 255) / 2);
            count++;
        }
        for (int slot = 0; slot < pendingNibWrites.length; slot++) {
            if (!pendingNibWrites[slot]) continue;
            int index = entry(candidate, slot + 2);
            if (index < 0) {
                if (slot / 2 + 1 > recordedTracks && extendImageListener != null && !extendImageListener.isAllowed())
                    throw new IOException("NIB track extension was declined");
                int limit = nibHeader[13] == 2 ? MAX_NB2_SIZE : MAX_NIB_SIZE;
                if (count == MAX_TRACKS_1541 * 2 || candidate.length > limit - recordSize)
                    throw new IOException("NIB image has no room for an additional capture");
                int end = 256 + count * recordSize;
                byte[] expanded = new byte[candidate.length + recordSize];
                System.arraycopy(candidate, 0, expanded, 0, end);
                System.arraycopy(candidate, end, expanded, end + recordSize, candidate.length - end);
                candidate = expanded;
                index = 16 + count++ * 2;
                candidate[index] = (byte) (slot + 2);
                candidate[index + 2] = 0;
                if ((slot & 1) != 0) candidate[15] |= 1;
                recordedTracks = Math.max(recordedTracks, slot / 2 + 1);
            }
            byte[][] samples = trackCycles[slot + 2];
            byte[] speeds = recordedNibSpeeds[slot];
            int zone = speeds[0], length = getHalfTrackSize(slot + 2, 0);
            candidate[index + 1] = (byte) (zone | signalFlags(samples[0], length));
            int offset = 256 + (index - 16) / 2 * recordSize;
            int passes = nibHeader[13] == 2 ? 4 : 1;
            if (passes == 4) offset += zone * 4 * MNIB_TRACK_LENGTH;
            for (int pass = 0; pass < passes; pass++) {
                byte[] data = samples[pass % samples.length];
                for (int i = 0; i < MNIB_TRACK_LENGTH; i++) candidate[offset + pass * MNIB_TRACK_LENGTH + i] = data[i % length];
            }
        }
        byte[] encoded = encodeImageData(candidate);
        byte[] original = new byte[(int) fd.length()];
        fd.seek(0);
        fd.readFully(original);
        try {
            fd.seek(0);
            fd.write(encoded);
            fd.setLength(encoded.length);
        } catch (IOException failure) {
            try {
                fd.seek(0);
                fd.write(original);
                fd.setLength(original.length);
            } catch (IOException rollback) {
                failure.addSuppressed(rollback);
            }
            throw failure;
        }
        sourceImage = candidate;
        System.arraycopy(candidate, 0, nibHeader, 0, nibHeader.length);
        Arrays.fill(pendingNibWrites, false);
    }

    protected byte[] encodeImageData(byte[] image) throws IOException {
        return image;
    }

    private static int signalFlags(byte[] data, int length) {
        boolean allSync = true, sync = false;
        int ones = 0;
        for (int bit = 0; bit < length * 8 + 9; bit++) {
            if (((data[bit / 8 % length] >>> (7 - (bit & 7))) & 1) != 0) {
                if (++ones >= 10) sync = true;
            } else {
                allSync = false;
                ones = 0;
            }
        }
        return allSync ? 0x80 : sync ? 0 : 0x40;
    }

    @Override
    void gcrHalfTrackWriteback(int halfTrack, int side) throws IOException {
        if (side != 0 || halfTrack < 2 || halfTrack > MAX_TRACKS_1541 * 2 + 1)
            throw new IOException("Invalid NIB recording position: " + halfTrack + "/" + side);
        if (isReadOnly()) throw new IOException("Disk is write protected");
        int slot = halfTrack - 2;
        if (!pendingNibWrites[slot]) {
            byte[] bytes = surface(slot), speeds = new byte[bytes.length];
            Arrays.fill(speeds, (byte) density((halfTrack & 1) != 0 && halfTrackData[slot / 2] == null ? halfTrack - 1 : halfTrack));
            installRecording(slot, new byte[][]{bytes}, speeds);
        }
        flushPendingGCRWrites();
    }

    /**
     * Try to extract one complete cycle of GCR data from an 8kB buffer. Align track
     * to a sector gap if possible, else align to sector 0, else copy the cycle
     * from the beginning of the source. Without a recoverable period, preserve
     * flagged protection signals at nominal density or use the legacy blank policy.
     */
    private Surface extractSurface(byte[] src, int flags, int track) throws IOException {
        byte[] dest = new byte[GCR.NUM_MAX_BYTES_TRACK];
        Arrays.fill(dest, (byte) 0xff);
        /* start position of cycle */
        /* stop position of cycle */
        TrackCycle cycle = new TrackCycle(0, 0);
        /* position of sector 0 */
        int sector0Pos;
        /* position of a sector gap */
        int sectorGapPos;

        boolean exact = findExactTrackCycle(src, cycle);
        if (!exact) findTrackCycle(src, cycle);
        int trackLen = cycle.cycleStop - cycle.cycleStart;
        if (trackLen == 0) {
            if ((flags & 0x40) != 0) {
                byte[] bits = NIBBitCycle.extract(src, MIN_TRACK_LENGTH);
                if (bits != null) {
                    System.arraycopy(bits, 0, dest, 0, bits.length);
                    return new Surface(dest, bits.length, 3, src);
                }
            }
            if ((flags & 0xc0) != 0) {
                // NIBTools marks no-SYNC and all-SYNC tracks explicitly. No period
                // is inferable here; preserve their signal at the declared density.
                trackLen = RAW_TRACK_SIZE[flags & 3];
                System.arraycopy(src, 0, dest, 0, trackLen);
                return new Surface(dest, trackLen, 1, src);
            }
            trackLen = RAW_TRACK_SIZE[SPEED_MAP_1541[track]];
            Arrays.fill(dest, (byte) 0x55);
            dest[0] = (byte) 0xff;
            return new Surface(dest, trackLen, 0, src);
        }
        if (trackLen > dest.length) {
            throw new IOException("Unsupported NIB revolution length: " + trackLen);
        }
        /* working buffer */
        byte[] gcrData = new byte[MNIB_TRACK_LENGTH << 1];
        /* copy twice the data to the work buffer */
        System.arraycopy(src, cycle.cycleStart, gcrData, 0, trackLen);
        System.arraycopy(src, cycle.cycleStart, gcrData, trackLen, trackLen);

        if (-1 != (sectorGapPos = findSectorGap(gcrData, trackLen))) {
            System.arraycopy(gcrData, sectorGapPos, dest, 0, trackLen);
        } else if (-1 != (sector0Pos = findSector0(gcrData, trackLen))) {
            System.arraycopy(gcrData, sector0Pos, dest, 0, trackLen);
        } else {
            System.arraycopy(gcrData, 0, dest, 0, trackLen);
        }
        return new Surface(dest, trackLen, exact ? 3 : 2, src);
    }

    /**
     * A capture need not contain two copies of a SYNC edge. Prefer a complete
     * matching byte overlap when it contains enough distinct data to avoid
     * inferring a rotation length from constant or short repeating gap bytes.
     * Retain the SYNC heuristic below for captures whose repeated area differs
     * (e.g. weak bits); NIB does not supply a definitive revolution length.
     */
    private boolean findExactTrackCycle(byte[] source, TrackCycle cycle) {
        boolean[] seen = new boolean[256];
        int[] distinct = new int[source.length + 1];
        for (int i = 0; i < source.length; i++) {
            int value = source[i] & 0xff;
            distinct[i + 1] = distinct[i] + (seen[value] ? 0 : 1);
            seen[value] = true;
        }
        for (int length = MIN_TRACK_LENGTH; length <= source.length - MATCH_LENGTH; length++) {
            int overlap = source.length - length;
            if (distinct[overlap] >= MATCH_LENGTH && equals(source, 0, length, overlap)) {
                cycle.cycleStart = 0;
                cycle.cycleStop = length;
                return true;
            }
        }
        return false;
    }

    private int findTrackCycle(byte[] gcrData, TrackCycle cycle) {
        /* start of nibbled track data */
        int nibTrack = cycle.cycleStart;
        /* maximum position allowed for cycle */
        int stopPos = nibTrack + MNIB_TRACK_LENGTH - MATCH_LENGTH;

        for (int startPos = nibTrack; true; ) {
            /* cycle search variable */
            int syncPos;
            if ((syncPos = startPos + MIN_TRACK_LENGTH) >= stopPos) {
                cycle.cycleStop = cycle.cycleStart;
                return 0; /* no cycle found */
            }

            /* try to find the next sync */
            while ((syncPos = findSync(gcrData, syncPos, stopPos)) != -1) {
                /* found a sync, now let's see if the data matches */
                int p1 = startPos;
                /* start of cycle repetition */
                int cycle_pos = syncPos;
                for (int p2 = cycle_pos; p2 < stopPos; ) {
                    /* try to match all remaining syncs, too */
                    if (!equals(gcrData, p1, p2, MATCH_LENGTH)) {
                        cycle_pos = -1;
                        break;
                    }
                    if ((p1 = findSync(gcrData, p1, stopPos)) == -1) {
                        break;
                    }
                    if ((p2 = findSync(gcrData, p2, stopPos)) == -1) {
                        break;
                    }
                }

                if (cycle_pos != -1) {
                    cycle.cycleStart = startPos;
                    cycle.cycleStop = cycle_pos;
                    return cycle_pos - startPos;
                }
            }
            startPos = findSync(gcrData, startPos, stopPos);
            if (startPos == -1) {
                startPos = stopPos;
            }
        }
    }

    private boolean equals(byte[] gcrData, int from, int to, int length) {
        for (int i = 0; i < length; i++) {
            if (gcrData[from + i] != gcrData[to + i]) {
                return false;
            }
        }
        return true;
    }

    private int findSector0(byte[] gcrData, int tracklen) {
        int pos = 0;
        int bufferEnd = 2 * tracklen - 10;

        /* try to find sector 0 */
        while (pos < bufferEnd) {
            if ((pos = findSync(gcrData, pos, bufferEnd)) == -1) {
                return -1;
            }
            if (gcrData[pos] == 0x52 && (gcrData[pos + 1] & 0xc0) == 0x40 && (gcrData[pos + 2] & 0x0f) == 0x05
                    && (gcrData[pos + 3] & 0xfc) == 0x28) {
                break;
            }
        }

        /* find last GCR byte before sync */
        do {
            pos--;
            if (pos == 0) {
                pos += tracklen;
            }
        } while (gcrData[pos] == (byte) 0xff);

        /* move to first sync GCR byte */
        pos++;
        while (pos >= tracklen) {
            pos -= tracklen;
        }

        return pos;
    }

    private int findSync(byte[] gcrData, int pos, int gcrEnd) {
        while (true) {
            if (pos + 1 >= gcrEnd) {
                pos = gcrEnd;
                return -1; /* not found */
            }
            if ((gcrData[pos] & 0x03) == 0x03 && gcrData[pos + 1] == (byte) 0xff) {
                break;
            }
            pos++;
        }

        do {
            pos++;
        } while (pos < gcrEnd && gcrData[pos] == (byte) 0xff);
        return pos < gcrEnd ? pos : -1;
    }

    private int findSectorGap(byte[] gcrData, int tracklen) {
        int syncMax = 0;
        int pos = 0;
        int bufferEnd = (tracklen << 1) - 10;

        if ((pos = findSync(gcrData, pos, bufferEnd)) == -1) {
            return -1;
        }
        int syncLast = pos;
        int maxgap = 0;
        /* try to find the biggest (sector) gap */
        while (pos < bufferEnd) {
            if ((pos = findSync(gcrData, pos, bufferEnd)) == -1) {
                break;
            }
            int gap = pos - syncLast;
            if (gap > maxgap) {
                maxgap = gap;
                syncMax = pos;
            }
            syncLast = pos;
        }

        if (maxgap == 0) {
            return -1; /* no gap found */
        }

        /* find last GCR byte before sync */
        pos = syncMax;
        do {
            pos--;
            if (pos == 0) {
                pos += tracklen;
            }
        } while (gcrData[pos] == (byte) 0xff);

        /* move to first sync GCR byte */
        pos++;
        while (pos >= tracklen) {
            pos -= tracklen;
        }

        return pos;
    }

    @Override
    public void gcrDataWriteback(final int track) throws IOException {
        if (track < 1 || track > MAX_TRACKS_1541) throw new IOException("Invalid NIB track: " + track);
        gcrHalfTrackWriteback(track * 2, 0);
    }

}