%define	KERNEL_SEG	07F0h	; Kernel will start at 07F0:0000

	ORG	7C00h

	JMP	SHORT START
	NOP

	; Partition information (only labelled entries are actually used)
			DB	'SHITOS01'
			DW	512
			DB	1
RESERVED_SECTORS	DW	2		; Reserved sectors
			DB	1
			DW	0
			DW	0
			DB	0
			DW	0
			DW	0
			DW	1
			DD	0
			DD	0
			DW	0		; Logical drive number
FILESYS_SECTORS		DB	3		; Number of sectors for FS
			DD	0
			DB	'SHITOS     '
			DB	'SFS     '

START:
	; Set up segment registers
	XOR	AX, AX
	MOV	DS, AX
	MOV	AX, KERNEL_SEG
	MOV	ES, AX

	CALL	PRINT
	DB	'Loading ShitOS...', 0Dh, 0Ah, 0Ah, 0

;	MOV	AL, DL
;	ADD	AL, '0'
;	MOV	DI, DN_CHR
;	STOSB
;	CALL	PRINT
;	DB	'Drive number: '
;DN_CHR	DB	20h, 0Dh, 0Ah, 0

	; Check if drive supports LBA addressing.
	MOV	AH, 041h
	MOV	BX, 55AAh
				; DL contains drive number
	INT	13h
	JNC	LBA_SUPPORTED
	CALL	PRINT
	DB	'LBA addressing is not supported.', 0Dh, 0Ah, 0
	JMP	TRY_READ
LBA_SUPPORTED:
	CALL	PRINT
	DB	'LBA addressing is supported.', 0Dh, 0Ah, 0

TRY_READ:
	; Load ShitOS
	MOV	AH, 02
	MOV	AL, RESERVED_SECTORS	; Number of sectors to read
	MOV	CX, 0002h	; Track 0, sector 1
	XOR	DH, DH		; Head 0
				; Drive number is already in DL
	XOR	BX, BX		; Load to the start of the kernel segment
	INT	13h
	JC	READ_ERROR

	; Set up segment registers for kernel
	MOV	AX, KERNEL_SEG
	MOV	DS, AX

	; Set up a stack
	MOV	SS, AX		; AX still contains KERNEL_SEG
	MOV	BP, 0FFFEh
	MOV	SP, BP
	MOV	[BP], WORD 0000
	

	; Give control to kernel
	CALL	KERNEL_SEG:0000h

	; Oh... got back?
	XOR	AX, AX
	MOV	DS, AX
	CALL	PRINT
	DB	'Returned to bootstrap loader.', 0Dh, 0Ah
	DB	'Press any key to reboot.', 0Dh, 0Ah, 0

	JMP	REBOOT


READ_ERROR:
	XOR	AH, AH		; Reset Disk System...
	INT	13h
	CALL	PRINT
	DB	'Read failure. Retrying...', 0Dh, 0Ah, 0
	CMP	[TRYCOUNT], BYTE 3
	MOV	AH, 1
	JAE	FAIL
	INC	BYTE [TRYCOUNT]
	JMP	TRY_READ

TRYCOUNT	DB	0

FAIL:
	CALL	PRINT
	DB	'Operation failed... Press any key to reboot!', 0

REBOOT:
	XOR	AH, AH
	INT	16h
	INT	19h
	; If INT 19h didn't take effect, halt the system
	CLI
	HLT


PRINT_0:
	XOR	BX, BX
	MOV	AH, 0Eh
	INT	10h
PRINT:
	POP	SI
	LODSB
	PUSH	SI
	CMP	AL, 0
	JNE	PRINT_0
	RET

	TIMES	01FEh-$+$$ DB 0

SIGN	DW	0AA55h
