BITS 16
jmp 07C0h:start

start:
    mov [drive], dl
    mov ax, cs
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov sp, 0ffffh
    mov si, txt0
    call printstring
rept:
    mov si, txt1
    call printstring
    mov ah, 0h
    int 16h
    cmp ah, 28
    jz startkernel
    mov si, txt3
    call printstring
    call printuns
    mov al, ah
    mov si, txt2
    call printstring
    call printuns
    jmp rept
startkernel:
    mov si, txt4
    call printstring
    mov ax, 020h	;segment where
    mov es, ax		;to load kernel
    mov dl, [drive]
    mov ah, 00h ;reset disk drive
    int 13h
    jc error1 ;display error message if drive reset failed
    mov si, txt7
    call printstring

    mov al, 1 ;read one sector
    mov cx, 02h ; cylinder 0, sector 2
    mov dh, 0 ;head 0
    mov bx, 0 ;address in segment es where to load kernel
    mov ah, 02h ; function to read from drive
    int 13h
    jc error2
    
    push ds
    push es
    mov bx, ss ;bx=old stack segment
    mov cx, sp ;cx=old stack pointer

    mov ax, 020h
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov sp, 0ffffh
    call 020h:0 ;call the kernel
    mov ss, bx
    mov sp, cx
    pop es
    pop ds
    jmp rept

error1:
    mov si, txt5
    call printstring
    jmp rept
error2:
    mov si, txt6
    call printstring
    jmp rept

;routine printstring: will print zero-terminated string from ds:si.
printstring:
    pusha
    pushf
    mov bx, 7 ;use the right page
    mov ah, 0Eh
nxtprintstring:
    lodsb
    or al, al
    jz endprintstring
    int 10h
    jmp nxtprintstring
endprintstring:
    popf
    popa
    ret

;routine printuns: will print unsigned integer in al
printuns:
    pusha
    pushf
    mov bh, al
    mov dl, 10
    mov bl, 100
nxtprintuns:
    and ax, 0000000011111111b
    div bl
    or al, 00110000b ;converting to ascii
    mov ah, 0Eh
    int 10h
    and al, 00001111b ;converting back from ascii
    mul bl
    sub bh, al
    mov al, bl
    div dl
    jz endprintuns
    mov bl, al
    mov al, bh
    jmp nxtprintuns
endprintuns:
    popf
    popa
    ret

txt0:
    db 0ah, 0dh, 'You are in REAL MODE: NO STRINGS ATTACHED! ',0
txt1:
    db 0ah, 0dh, 'Press a key (RETURN to enter the KERNEL)! ',0
txt2:
    db 0ah, 0dh, 'Scancode: ',0
txt3:
    db 0ah, 0dh, 'ASCII: ',0
txt4:
    db 0ah, 0dh, 'Will now reset disk drive...',0
txt5:
    db 0ah, 0dh, 'ERROR: UNABLE TO RESET DRIVE!',0
txt6:
    db 0ah, 0dh, 'ERROR: UNABLE TO LOAD KERNEL!',0
txt7:
    db 0ah, 0dh, 'Will now load kernel...',0
drive:
times 510-($-$$) db 0 ; Fill the file with 0s
dw 0AA55h

