;-------------------- 1.44MB BOOT SECTOR -----------------------
%define START   0x110000
        tib     equ 0x100000            ;Input buffer (grows upward);
        rp0     equ tib+400h            ;Return stack (grows down)
        sp0     equ rp0+100h            ;Data stack (grows down)
        d0      equ sp0+10h             ;Dictionary header space
        h0      equ START+50000
;-------------------- START BOOT SECTOR ------------------------
bits 16
org 0x7c00
	xor ax,ax	;Initialize segments
	mov ds,ax
      mov ss,ax
      mov sp,7000h
;-------------------- LOAD Retro IV ----------------------------
bootload:
	mov cx,3		;# retries
.retry
	push cx
	mov ax,7e0h 	;Load to es:bx -- address 7e00
	mov es,ax
	xor bx,bx
	xor cx,cx		;ch=0 (track)
	inc cl		;cl=2 (sector, 1-based)
	inc cl
	xor dx,dx		;dl=0 (drive)  dh=0 (head)
	mov ax,240h		;al=35 (sectors)
	int 0x13		;BIOS service $1302 - disk read

	jnc .success
	pop cx
	loop .retry
.error
	mov ax,0xb800
	mov es,ax
	mov [es:0],word 0x0445
	jmp short $
.success
	xor al,al		;shut off floppy motor
	mov dx,0x3f2
	out dx,al
       mov ax,0xb800
       mov es,ax
       mov [es:2],word 0x0445
;-------------------- ENTER PROTECTED MODE ---------------------
      call graphics
      call A20
      cli
	lgdt [gdt]
	mov eax,cr0
	inc eax
	mov cr0,eax
	jmp dword 8:protected
bits 32
protected:
	mov ax,0x10		;data seg
	mov ds,ax
	mov es,ax
	mov ss,ax
	mov esp,rp0		;return stack
	cld
        mov esi,7e00h   ;Move kernel
        mov edi,0x110000
        mov edx,edi
        mov ecx,(END-kernel)/4
        cld
        rep movsd
        mov esi,sp0     ;data stack
        call edx
        mov [0xb8004], word 0x0445
	jmp short $     ;Freeze if any problems arise
;----------------------- REQUIRED DATA -------------------------
 align 8
gdt:	dw 0x18
	dd gdt
	dw 0
	dw 0xffff, 0, 0x9a00, 0xcf	;code
	dw 0xffff, 0, 0x9200, 0xcf	;data
BITS 16
BITS 16
graphics:
%ifdef VESA
        push es
        push word 0x800
        pop es
        xor di,di
        mov ax,0x4F00
        int 10h
        pop es
        cmp ax,0x004F
        jz .vesa
%endif
        mov ax,13h              ;Graphics mode
	int 10h
        ret
%ifdef VESA
.vesa   mov ax,0x4F02
        mov bx,0x101
        int 0x10
        ret
%endif
A20:
        in al,92h               ;PS/2 version
        or al,2
        jmp short $+2
        jmp short $+2
        jmp short $+2
        out 92h,al
        ret
times	510-($-$$)	db 0		; skip to end of sector
	dw	0xAA55		; boot sector signature
kernel:
 incbin "retro"
 align 4
END
