#include <stdio.h>
#include <conio.h>
#include <stdint.h>

/*
 * attr_probe — visualise every value of the ESTEX attribute byte.
 *
 * Layout:
 *   row 2   16 cells: low nibble 0..F, high nibble 0   (varying fg)
 *   row 4   16 cells: low nibble 7, high nibble 0..F   (varying bg)
 *   row 6   bit-7 toggle test: 8 pairs comparing N with N|0x80
 *   row 8   full 16x16 grid: bg outer, fg inner — every attribute byte
 *   row 26  RDCHAR readback of a known cell
 *
 * Each cell is drawn with wrchar() so the attribute is set exactly,
 * independent of ESTEX's hidden "current" attribute used by PCHARS.
 */

int main(void)
{
    clrscr();

    gotoxy(20, 0); cputs("== attr probe ==");

    /* Row 2: vary fg (low nibble), bg = 0 (black). */
    gotoxy(0, 2);  cputs("fg 0..F /bg0:");
    for (int i = 0; i < 16; i++) {
        wrchar(15 + i, 2, 'A' + i, (uint8_t)i);
    }

    /* Row 4: vary bg (high nibble), fg = 7 (light gray). */
    gotoxy(0, 4);  cputs("bg 0..F /fg7:");
    for (int i = 0; i < 16; i++) {
        wrchar(15 + i, 4, 'A' + i, (uint8_t)((i << 4) | 0x07));
    }

    /* Row 6: compare attr N with N|0x80 — bit 7 may be blink or extra bg. */
    gotoxy(0, 6);  cputs("bit7: N|N|0x80 pairs (1F,2E,3D,4C,5B,6A,79,F0):");
    {
        static const uint8_t probes[] = { 0x1F, 0x2E, 0x3D, 0x4C,
                                          0x5B, 0x6A, 0x79, 0xF0 };
        for (int i = 0; i < 8; i++) {
            wrchar(2 + i*4,     7, '*', probes[i]);
            wrchar(2 + i*4 + 1, 7, '*', probes[i] | 0x80);
            /* hex labels under each pair */
            gotoxy(2 + i*4, 8);
            printf("%02X", probes[i]);
        }
    }

    /* Row 10..25: full 16x16 grid of every attr byte 0x00..0xFF.
     * Cell (col, row) = (col_idx + offset, row_idx + 10) holds char '#'
     * with attr = (row_idx << 4) | col_idx. */
    gotoxy(0, 10); cputs("Full 16x16 grid (row=bg, col=fg):");
    for (int row = 0; row < 16; row++) {
        for (int col = 0; col < 16; col++) {
            uint8_t attr = (uint8_t)((row << 4) | col);
            wrchar(20 + col, 11 + row, '#', attr);
        }
        /* label rows */
        gotoxy(15, 11 + row);
        printf("%X:", row);
    }
    gotoxy(20, 27);
    cputs("0123456789ABCDEF  (fg)");

    /* RDCHAR readback test. */
    {
        uint16_t got = rdchar(15, 2);
        gotoxy(0, 29);
        printf("rdchar(15,2) -> ch=0x%02X attr=0x%02X (expected 'A'=0x41 attr=0x00)",
               got & 0xFF, (got >> 8) & 0xFF);
    }

    gotoxy(0, 31);
    cputs("press any key");
    getch();
    return 0;
}
