; ===========================================================================
; CO-EMERGENT CLOSURE-RETURN SPHERICAL MACHINE  — STAGE 1 MBR
; BIOS loads at 0x0000:0x7C00
; Loads 16 sectors from LBA 1 into 0x0000:0x8000, jumps there.
; On failure: writes error directly to VGA 0xB800 (no BIOS).
; ===========================================================================
BITS 16
ORG 0x7C00

    cli
    xor   ax, ax
    mov   ds, ax
    mov   es, ax
    mov   ss, ax
    mov   sp, 0x7C00
    sti

    ; save boot drive from BIOS
    mov   byte [boot_drv], dl

    ; clear screen via int 10
    mov   ax, 0x0003
    int   0x10

    ; print stage1 banner via BIOS
    mov   si, msg_ok
    call  bios_puts

    ; --- try EDD read ---
    mov   ah, 0x41
    mov   bx, 0x55AA
    mov   dl, byte [boot_drv]
    int   0x13
    jc    .try_chs
    cmp   bx, 0xAA55
    jne   .try_chs

    ; EDD supported: build DAP at [dap]
    mov   word [dap],    0x0010  ; size=16, reserved=0
    mov   word [dap+2],  16       ; sectors to read
    mov   word [dap+4],  0x8000  ; buffer offset
    mov   word [dap+6],  0x0000  ; buffer segment
    mov   dword [dap+8], 1       ; LBA low = 1
    mov   dword [dap+12],0       ; LBA high = 0
    mov   si, dap
    mov   ah, 0x42
    mov   dl, byte [boot_drv]
    int   0x13
    jnc   .go
    ; EDD failed, fall through

.try_chs:
    mov   ax, 0x0210   ; AH=02 read, AL=16 sectors
    mov   bx, 0x8000    ; buffer at 0:0x8000
    mov   cx, 0x0002    ; cylinder 0, sector 2 (1-based)
    mov   dh, 0x00      ; head 0
    mov   dl, byte [boot_drv]
    int   0x13
    jnc   .go

    ; Both failed: write ERR directly to VGA 0xB800:0002 (row0 col1)
    mov   ax, 0xB800
    mov   es, ax
    mov   word [es:0x0002], 0x4F45  ; 'E' attr=0x4F (white on red)
    mov   word [es:0x0004], 0x4F52  ; 'R'
    mov   word [es:0x0006], 0x4F52  ; 'R'
    cli
    hlt

.go:
    ; jump to stage2
    xor   ax, ax
    mov   es, ax
    mov   ds, ax
    jmp   0x0000:0x8000

bios_puts:
    lodsb
    test  al, al
    jz    .d
    mov   ah, 0x0E
    xor   bx, bx
    int   0x10
    jmp   bios_puts
.d: ret

msg_ok   db "HDGL SUBSTRATE: stage1 ok, loading..",13,10,0
boot_drv db 0

; DAP built at runtime
dap: times 16 db 0

times 510-($ - $$) db 0
dw 0xAA55
