BITS 16
ORG 0x7C00
CPU 386
jmp near START
nop

OEM_ID db "PARADIGM"
BytesPerSector dw 0x0200
SectorsPerCluster db 0x02
ReservedSectors dw 0x0001
TotalFATs db 0x01
MaxRootEntries dw 0x0016
TotalSectors dw 0x0B90
MediaDescriptor db 0xF0
SectorsPerFAT dw 0x0009
SectorsPerTrack dw 0x0003
NumHeads dw 0x0002
HiddenSectors dd 0x00000000
TotalSectorsLarge dd 0x00000000
Flags  dw 0x0000
FSVersion dw 0x0000
RootDirectoryStart dw 0x00000002
FSInfoSector dw 0x0000
BackupBootSector dw 0x0000
times 13 db 0
BigSectorsPerFAT dd 0x00000001
DriveNumber db 0x00
Signature db 0x29
VolumeID dd 0xFFFFFFFF
VolumeLabel db "PARADIGM-OS"
SystemID db "FAT32   "

START:
cli
mov ax, 0x0000
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ax, 0x7A00
mov ss, ax
mov sp, 0x7C00
sti
mov si, msgLoading ;display loading message
call DisplayMessage
mov cx, WORD [SectorsPerCluster] ;read 2 sectors
xor ax, ax
mov al, BYTE [TotalFATs]
mul WORD [BigSectorsPerFAT]
add ax, WORD [ReservedSectors]
mov WORD [datasector], ax
xor ax, ax
mov ax, WORD [RootDirectoryStart]
call ClusterLBA
mov bx, 0x0200
call ReadSectors
jmp DONE

DONE:
mov si, msgSuccess
call DisplayMessage
jmp end

FAILURE:
mov si, msgFailure
call DisplayMessage
hlt

DisplayMessage:
lodsb
or al, al
jz .DONE
mov ah, 0x0E
mov bh, 0x00
mov bl, 0x07
int 0x10
jmp DisplayMessage
.DONE:
ret

;Read 'cx' sectors starting from memory location 'ax' into memory location 'bx'
ReadSectors:
.MAIN:
mov di, 5 ;5 tries total
.SECTORLOOP:
push ax
push bx
push cx
call LBACHS
mov ah, 0x02
mov al, 0x01
mov ch, BYTE [absoluteTrack]
mov cl, BYTE [absoluteSector]
mov dh, BYTE [absoluteHead]
mov dl, BYTE [DriveNumber]
int 0x13
jnc .SUCCESS
xor ah, ah
int 0x13
dec di
pop cx
pop bx
pop ax
jnz .SECTORLOOP
int 0x18
.SUCCESS:
mov si, msgProgress
call DisplayMessage
pop cx
pop bx
pop ax
add bx, WORD [BytesPerSector]
inc ax
loop .MAIN
ret

ClusterLBA:
sub ax, 0x0002
xor cx, cx
mov cl, BYTE [SectorsPerCluster]
mul cx
add ax, WORD [datasector]
ret

LBACHS:
xor dx, dx
div WORD [SectorsPerTrack]
inc dl
mov BYTE [absoluteSector], dl
xor dx, dx
div WORD [NumHeads]
mov BYTE [absoluteHead], dl
mov BYTE [absoluteTrack], al
ret

absoluteSector db 0x00
absoluteHead db 0x00
absoluteTrack db 0x00

datasector dw 0x0000
cluster dw 0x0000
msgLoading db "Loading Boot Image", 0x0D, 0x0A, 0x00
msgCRLF db 0x0D, 0x0A, 0x00
msgProgress db ".", 0x00
msgFailure db 0x0D, 0x0A, "ERROR: Press Any Key to Reboot", 0x00
msgSuccess db "DONE"

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

end:
