; Linked at the start of a segment, so the copy can have the same offset in its
; segment as the original code has.
[ORG 0x00]
[BITS 16]

%define copy_seg   0x060                  ; traditional MBR relocation?
%define boot_seg   0x7C0                  ; boot sector gets loaded here

%define bootsector  (boot_seg * 0x10)
%define stack       bootsector              ; stack just before boot sector

%define drive       0x80

origin:
    jmp boot_seg:start			; Jump to segment:offset assembled for.
    
start:
    cli
    
    ; Make sure SP and SS contain reasonable values.
    mov SP, stack
    xor AX, AX
    mov SS, AX
    
    ;; Copy boot sector data to a different address
    
    ; Addres registers
    mov AX, boot_seg
    mov DS, AX                      ; original segment
    mov SI, copy_start              ; original address
    ; Copy to same offset in a different segment:
    mov AX, copy_seg
    mov ES, AX                      ; destination segment
    mov DI, copy_start              ; destination address
    
    ; length
    mov CX, (copy_end - copy_start)
    
    rep movsb
    
    jmp copy_seg:copy_start         ; long jump to copied code
    
copy_start:
    ;; Load second sector on disk to 0x0:0x7C00
    
; Quote from RBIL (Ralf Brown's Interrupt List) [file: INTERRUP.B]:
;
;INT 13 - DISK - READ SECTOR(S) INTO MEMORY
;	AH = 02h
;	AL = number of sectors to read (must be nonzero)
;	CH = low eight bits of cylinder number
;	CL = sector number 1-63 (bits 0-5)
;	     high two bits of cylinder (bits 6-7, hard disk only)
;	DH = head number
;	DL = drive number (bit 7 set for hard disk)
;	ES:BX -> data buffer
;Return: CF set on error
;	    if AH = 11h (corrected ECC error), AL = burst length
;	CF clear if successful
;	AH = status (see #00234)
;	AL = number of sectors transferred (only valid if CF set for some
;	      BIOSes)
    
    xor AX, AX
    mov ES, AX              ; segment 0
    mov BX, bootsector
    
    mov AH, 2               ; read sectors
    mov AL, 1               ; one of them
    mov CH, 0               ; cylinder (low 8 bits)
    mov CL, 1               ; sector 1, upper 2 bits of cylinder 0
    mov DH, 0               ; head
    mov DL, drive           ; drive number
    int 0x13
    
    ; Carry set on error
    jnc done
    
    ; Some sort of error, reset drive
reset:
    mov AH, 0               ; reset drive
    mov DL, drive           ; drive number
    int 0x13
    
    jc reset                ; can't even _reset_ properly? Try again!
    
    jmp copy_start
    
done:
    ; Set DL to chainloaded drive
    mov DL, drive
    
    ; Jump to chainloaded bootsector
    jmp 0x0:bootsector
    
    
copy_end:
    ; This is where the initial code stops copying
    
    times (510 - ($ - $$)) db 0
    db 0x55, 0xAA