[BITS 16]       			; We need 16-bit intructions for Real mode

[ORG 0]

jmp 0x07c0:stage1

stage1:
	push ax
	push bx
	push cx
	push dx
	mov ax, 0x07C0		; Lets initialize segment registers to where we are loaded
	mov ds, ax
	mov es, ax
	mov fs, ax
	mov gs, ax
	cli
	mov ss,ax
	mov sp,0x9000
	sti
	mov byte [bootdrv],dl			; save the drive we booted from (very important)
	mov eax,0
	call display_boot_msg
	pop dx
	pop cx
	pop bx
	pop ax
	mov di,0			; We'll increment DI everytime we fail to load the kernel
	jmp load_kernel


display_boot_msg:

		mov si,bootmsg 		; Display our boot message via printmessage call
		call printmessage
		ret				; return to calling function
	 
	printmessage:			; Dump ds:si to screen.

                lodsb              	; load byte at ds:si into al
                cmp al,0            ; test if character is 0 (end)
                jz return		; if end then return
                mov ah,0eh          ; put character
                mov bx,0007         ; attribute
                int 0x10            ; call BIOS
                jmp printmessage

	return:
		ret				; return to calling function

Failed:
	mov SI,load_error
	call printmessage
	cli
	hlt
	
load_kernel:
		push ax
		push bx
		push cx
		push dx

		inc di
		cmp di,10			; Check if we have tried 10 times to load the kernel
		jz Failed

        	mov ah, 0               ; RESET-command
        	int 13h                 ; Call interrupt 13h
        	or ah, ah               ; Check for error code
        	jnz load_kernel         ; Try again if ah != 0

        	mov ax, 0
        	mov es, ax
        	mov bx, 0x7E00	      ; Destination address of our sample kernel= 0000:7E00

       	mov ah, 2h              ; READ SECTOR-command
        	mov al, 1             	; No. of sectors to read=1
        	mov ch, 0               ; Cylinder = 0
        	mov cl, 02h            	; Starting sector=2
		mov dl,[bootdrv]		; Drive = Our boot drive
        	mov dh, 0               ; Head = 0
						
        	int 13h                 ; Call interrupt 13h
        	or ah, ah               ; Check for error code
        	jnz load_kernel         ; Try again if ah != 0
		pop dx
		pop cx
		pop bx
		pop ax
		jmp 0x07E0:0x0000		; Jump to kernel address

		bootmsg db "Loading .....",0
		load_error db "Unable to load sample kernel!",0
		bootdrv db 0


times 510-($-$$) db 0           ; Fill up the file with zeros			


        dw 0AA55h                ; Boot sector identifyer
