/*
 * EXTCMOS.C - CMOS & Floppy utility for Sharp AX386HD (Phoenix 386 BIOS 1.10)
 *
 * Compile with Open Watcom (16-bit DOS):
 *   wcl -bt=dos extcmos.c
 *
 * Usage:
 *   EXTCMOS                  - Clear ext error flag (0x40 bit 3) & fix checksums
 *   EXTCMOS single           - Enable ONLY Floppy 0 (1.44MB); disable 1, 2, 3
 *   EXTCMOS fdd=4,0,0,0      - Set Floppy 0,1,2,3 types (0=None,1=360K,2=1.2M,3=720K,4=1.44M)
 *   EXTCMOS hd0=2            - Set HD0 drive type (0=None, 1..47 from BIOS table)
 *   EXTCMOS probe            - Probe MFM/AT controller (1F0-1F7) & INT 13h drive 80h
 *   EXTCMOS 4E=00 4F=01      - Set raw CMOS registers (hex, 10..7D) & fix checksums
 */

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

#if defined(__TURBOC__)
#define INB(p)      inportb(p)
#define OUTB(p, v)  outportb(p, v)
#define CLI()       disable()
#define STI()       enable()
#else
#define INB(p)      ((unsigned char)inp(p))
#define OUTB(p, v)  outp(p, v)
#define CLI()       _disable()
#define STI()       _enable()
#endif

static unsigned char read_cmos(unsigned char reg)
{
    unsigned char val;
    CLI();
    OUTB(0x70, reg | 0x80);
    val = INB(0x71);
    OUTB(0x70, 0x0D);
    STI();
    return val;
}

static void write_cmos(unsigned char reg, unsigned char val)
{
    CLI();
    OUTB(0x70, reg | 0x80);
    OUTB(0x71, val);
    OUTB(0x70, 0x0D);
    STI();
}

static unsigned int calc_sum(unsigned char start_reg, unsigned char end_reg)
{
    unsigned int sum = 0;
    unsigned char r;
    for (r = start_reg; r <= end_reg; r++) {
        sum += read_cmos(r);
    }
    return sum & 0xFFFF;
}

static void update_checksums(void)
{
    unsigned int std_sum, ext_sum;

    /* Standard AT CMOS checksum: sum(0x10..0x2D) -> 0x2E:0x2F (big-endian) */
    std_sum = calc_sum(0x10, 0x2D);
    write_cmos(0x2E, (unsigned char)((std_sum >> 8) & 0xFF));
    write_cmos(0x2F, (unsigned char)(std_sum & 0xFF));

    /* Extended CMOS checksum: sum(0x40..0x7D) -> 0x7E:0x7F (big-endian) */
    ext_sum = calc_sum(0x40, 0x7D);
    write_cmos(0x7E, (unsigned char)((ext_sum >> 8) & 0xFF));
    write_cmos(0x7F, (unsigned char)(ext_sum & 0xFF));
}

static void set_floppies(int f0, int f1, int f2, int f3)
{
    unsigned char eq;
    int count = 0;

    /* 0x68 = Internal FDD 0 (hi) & 1 (lo); 0x69 = External FDD 2 (hi) & 3 (lo) */
    write_cmos(0x68, (unsigned char)(((f0 & 0x0F) << 4) | (f1 & 0x0F)));
    write_cmos(0x69, (unsigned char)(((f2 & 0x0F) << 4) | (f3 & 0x0F)));

    /* 0x4C / 0x4D = 0x00 (normal internal bank A:/B:) */
    write_cmos(0x4C, 0x00);
    write_cmos(0x4D, 0x00);

    /* Standard CMOS 0x10 = Drive A (hi) & Drive B (lo) */
    write_cmos(0x10, (unsigned char)(((f0 & 0x0F) << 4) | (f1 & 0x0F)));

    /* Standard CMOS 0x14 (Equipment byte): bit 0 = FDD present, bits 7-6 = (count-1) */
    if (f0) count++;
    if (f1) count++;
    eq = read_cmos(0x14) & 0x3E; /* keep bits 5..1, clear bits 7..6 & bit 0 */
    if (count > 0) {
        eq |= 0x01;
        if (count > 1) eq |= 0x40;
    }
    write_cmos(0x14, eq);
}

static void print_hd(const char *name, int type)
{
    unsigned char __far *fdpt;
    unsigned int cyl, wpcom, lzone;
    unsigned char heads, spt;
    unsigned long mb10;

    if (type <= 0) {
        printf("  %s: Type 0 (None)\n", name);
        return;
    }
    if (type > 47) {
        printf("  %s: Type %d (Invalid > 47)\n", name, type);
        return;
    }
    fdpt = (unsigned char __far *)(((unsigned long)0xF000 << 16) |
                                   (unsigned int)(0xE401 + (type - 1) * 16));
    cyl   = fdpt[0] | ((unsigned int)fdpt[1] << 8);
    heads = fdpt[2];
    wpcom = fdpt[5] | ((unsigned int)fdpt[6] << 8);
    lzone = fdpt[12] | ((unsigned int)fdpt[13] << 8);
    spt   = fdpt[14];
    if (cyl == 0) {
        printf("  %s: Type %d (Empty slot)\n", name, type);
        return;
    }
    mb10 = ((unsigned long)cyl * heads * spt * 5UL) / 1024UL; /* tenths of MB */
    printf("  %s: Type %2d -> %u cyl, %u hd, %u spt (wpcom=%u, lz=%u, %lu.%lu MB)\n",
           name, type, cyl, heads, spt, wpcom, lzone, mb10 / 10UL, mb10 % 10UL);
}

static void set_hd0(int type)
{
    unsigned char r12 = read_cmos(0x12) & 0x0F;
    if (type <= 0) {
        write_cmos(0x12, r12);
        write_cmos(0x19, 0x00);
    } else if (type < 15) {
        write_cmos(0x12, (unsigned char)((type << 4) | r12));
        write_cmos(0x19, 0x00);
    } else {
        write_cmos(0x12, (unsigned char)(0xF0 | r12));
        write_cmos(0x19, (unsigned char)(type & 0xFF));
    }
}

static void print_status_bits(unsigned char st)
{
    printf("0x%02X [", st);
    if (st & 0x80) printf("BSY ");
    if (st & 0x40) printf("DRDY ");
    if (st & 0x20) printf("DWF ");
    if (st & 0x10) printf("DSC ");
    if (st & 0x08) printf("DRQ ");
    if (st & 0x01) printf("ERR");
    printf("]");
}

static void probe_hd(void)
{
    union REGS r;
    unsigned char st0, st1, alt, err;
    unsigned int i;

    printf("\nProbing MFM/AT Hard Disk Controller (ports 0x1F0-0x1F7, 0x3F6):\n");
    alt = INB(0x3F6);
    st0 = INB(0x1F7);
    err = INB(0x1F1);
    printf("  Initial Status(1F7)=");
    print_status_bits(st0);
    printf("  AltStat(3F6)=0x%02X  Err(1F1)=0x%02X\n", alt, err);

    if (st0 == 0xFF && alt == 0xFF) {
        printf("  -> Floating bus (0xFF): No AT/MFM controller responding at 0x1F0.\n");
    } else {
        /* Select Drive 0 (0xA0) and wait briefly */
        OUTB(0x1F6, 0xA0);
        for (i = 0; i < 1000; i++) INB(0x3F6);
        st0 = INB(0x1F7);
        printf("  Drive 0 (1F6=A0) Status=");
        print_status_bits(st0);
        printf("\n");

        /* Select Drive 1 (0xB0) */
        OUTB(0x1F6, 0xB0);
        for (i = 0; i < 1000; i++) INB(0x3F6);
        st1 = INB(0x1F7);
        printf("  Drive 1 (1F6=B0) Status=");
        print_status_bits(st1);
        printf("\n");

        /* Restore Drive 0 selection */
        OUTB(0x1F6, 0xA0);
    }

    printf("\nProbing via BIOS INT 13h (DL=0x80):\n");

    r.h.ah = 0x14; r.h.dl = 0x80;
    int86(0x13, &r, &r);
    printf("  AH=14h (Ctrl Diag):   %s (AH=0x%02X)\n",
           r.x.cflag ? "FAIL" : "PASS", r.h.ah);

    r.h.ah = 0x10; r.h.dl = 0x80;
    int86(0x13, &r, &r);
    printf("  AH=10h (Test Ready):  %s (AH=0x%02X)\n",
           r.x.cflag ? "FAIL" : "PASS", r.h.ah);

    r.h.ah = 0x11; r.h.dl = 0x80;
    int86(0x13, &r, &r);
    printf("  AH=11h (Recalibrate): %s (AH=0x%02X)\n",
           r.x.cflag ? "FAIL" : "PASS", r.h.ah);

    r.h.ah = 0x08; r.h.dl = 0x80;
    int86(0x13, &r, &r);
    if (r.x.cflag) {
        printf("  AH=08h (Get Params):  FAIL (AH=0x%02X)\n", r.h.ah);
    } else {
        unsigned int max_cyl = ((unsigned int)(r.h.cl & 0xC0) << 2) | r.h.ch;
        printf("  AH=08h (Get Params):  %u cyls, %u heads, %u spt (drives=%u)\n",
               max_cyl + 1, r.h.dh + 1, r.h.cl & 0x3F, r.h.dl);
    }
}

static void dump_regs(const char *label)
{
    unsigned char r68 = read_cmos(0x68);
    unsigned char r69 = read_cmos(0x69);
    unsigned char r12 = read_cmos(0x12);
    int hd0 = (r12 >> 4) & 0x0F;
    int hd1 = r12 & 0x0F;

    if (hd0 == 15) hd0 = read_cmos(0x19);
    if (hd1 == 15) hd1 = read_cmos(0x1A);

    printf("%s:\n", label);
    printf("  Std: 10(FDD)=%02X  12(HDD)=%02X  14(Equip)=%02X  2E:2F(Sum)=%02X%02X (Calc=%04X)\n",
           read_cmos(0x10), r12, read_cmos(0x14),
           read_cmos(0x2E), read_cmos(0x2F), calc_sum(0x10, 0x2D));
    print_hd("HD0", hd0);
    print_hd("HD1", hd1);
    printf("  Ext: 40(Err)=%02X  4C/4D(Mode)=%02X/%02X  4E(Key)=%02X  4F(Chip)=%02X\n",
           read_cmos(0x40), read_cmos(0x4C), read_cmos(0x4D),
           read_cmos(0x4E), read_cmos(0x4F));
    printf("       FDD0=%d  FDD1=%d  FDD2=%d  FDD3=%d  (68=%02X, 69=%02X)\n",
           (r68 >> 4) & 0x0F, r68 & 0x0F, (r69 >> 4) & 0x0F, r69 & 0x0F, r68, r69);
    printf("       7E:7F(Sum)=%02X%02X (Calc=%04X)\n",
           read_cmos(0x7E), read_cmos(0x7F), calc_sum(0x40, 0x7D));
}

int main(int argc, char *argv[])
{
    int i, f0, f1, f2, f3, do_probe = 0;
    unsigned int reg, val;

    dump_regs("Before");

    for (i = 1; i < argc; i++) {
        if (stricmp(argv[i], "single") == 0) {
            set_floppies(4, 0, 0, 0);
            printf("Configured single 1.44MB floppy: FDD0=4, FDD1=0, FDD2=0, FDD3=0\n");
        } else if (stricmp(argv[i], "probe") == 0) {
            do_probe = 1;
        } else if (sscanf(argv[i], "fdd=%d,%d,%d,%d", &f0, &f1, &f2, &f3) == 4) {
            set_floppies(f0, f1, f2, f3);
            printf("Configured floppies: FDD0=%d, FDD1=%d, FDD2=%d, FDD3=%d\n", f0, f1, f2, f3);
        } else if (sscanf(argv[i], "hd0=%d", &f0) == 1 && f0 >= 0 && f0 <= 47) {
            set_hd0(f0);
            printf("Configured HD0 = Type %d\n", f0);
        } else if (sscanf(argv[i], "%x=%x", &reg, &val) == 2 && reg >= 0x10 && reg <= 0x7D) {
            write_cmos((unsigned char)reg, (unsigned char)(val & 0xFF));
            printf("Set CMOS[%02X] = %02X\n", reg, val & 0xFF);
        } else {
            printf("Ignoring unknown argument '%s'\n", argv[i]);
        }
    }

    /* Clear bit 3 (0x08) of CMOS 0x40 (extended CMOS checksum error flag) */
    write_cmos(0x40, read_cmos(0x40) & (unsigned char)~0x08);

    update_checksums();
    dump_regs("After");
    if (do_probe) {
        probe_hd();
    }
    return 0;
}
