[bits 16]
[org 0x0]

jmp 0x7c0:_start

#include "stage1.h"

print:
	lodsb
	or al, al
	jz done
	mov ah, 0xe
	int 0x10
	jmp print
done:
	ret

reset_disk:
	mov ah, 0
	mov al, [bootdrv]
	int 0x13
	jc reset_error
	ret
reset_error:
	mov si, reset_error_msg
	jmp error
	
read_sector:
	mov si, progressmsg
	call print
	
	mov ah, 2                                            ;read sector
	mov al, 10                                           ;no of sectors to read
	mov cx, 2
	xor dx, dx
	mov dl, [bootdrv]                                    ;drive no
	int 0x13
	jc read_error

	mov si, eostr
	call print
	ret
	
read_next_sector:
	inc cl
	add bx, 0x200
	jmp read_sector
	
read_error:
	mov si, read_error_msg
	jmp error
	
load_stage2:
	mov si, stage2msg
	call print
	mov bx, STAGE2_LOC
	mov es, bx                                           ;segment=STAGE2_LOC
	xor bx, bx                                           ;offset=0
	call read_sector
	ret
	
_start:
	mov [bootdrv], dl                                    ;save boot drive number
	cli
	mov ax, cs
	mov ds, ax
	mov es, ax
	
	mov ss, ax
	mov sp, 0xfffe
	sti
	
	mov si, bootmsg
	call print
	
	call reset_disk
	
	call load_stage2
	
setupsegments:
	mov ax, STAGE2_LOC
	mov ds, ax
	mov es, ax
	mov fs, ax
	mov gs, ax
	mov ss, ax
	jmp  STAGE2_LOC:0x0000
	
	jmp _halt

error:
	call print
_halt:
	hlt
	jmp _halt

bootdrv: db 0
track: dw 0
sector: db 0
eostr: db 0xA, 0xD, 0x0
bootmsg: db "Loading gboot...", 0xA, 0xD, 0x0
stage2msg: db "Loading stage2", 0x0
progressmsg: db ".", 0x0
reset_error_msg: db "reset disk failed", 0xA, 0xD, 0x0
read_error_msg: db "read disk failed", 0xA, 0xD, 0x0
times 510 - ($ - $$) db 0

dw BIOS_SIG
