;----
; Scribbler: real-mode color etch-a-sketch.
; Use arrow keys to move, 1-8 to choose color, C to clear.
; TODO How do you do modulus in assembly?
;----

BITS 16
ORG 0x7C00

start:
	mov sp, 0x7C00
	; set video mode (640x480, 16 colors)
	mov ah, 0x00
	mov al, 0x12
	int 0x10

drawloop:
	; get a key
	mov ah, 0x00
	int 0x16
	
	call test_up_arrow
	call test_down_arrow
	call test_left_arrow
	call test_right_arrow
	call test_numbers
	call test_c
	call test_space

	test byte [drawing], 0b00000001
	jz .dontdraw
.draw:
	mov ah, 0x0C
	mov al, [color]
	mov bh, 0x00
	mov word cx, [xpos]
	mov word dx, [ypos]
	int 0x10

.dontdraw:
	jmp drawloop

test_up_arrow:
	cmp ah, 0x48
	jne .end
	sub word [ypos], 1
.end:
	ret

test_down_arrow:
	cmp ah, 0x50
	jne .end
	add word [ypos], 1
.end:
	ret

test_left_arrow:
	cmp ah, 0x4B
	jne .end
	sub word [xpos], 1
.end:
	ret

test_right_arrow:
	cmp ah, 0x4D
	jne .end
	add word [xpos], 1
.end:
	ret

test_numbers:
	; is this key between 0x02 (1) and 0x09 (8)?
	cmp ah, 0x02
	jl .end
	cmp ah, 0x09
	jg .end
	
	; it is: change the color
	mov byte [color], ah
	add byte [color], 0x06
.end:
	ret

test_space:
	cmp ah, 0x39
	jne .end
	not byte [drawing]
.end:
	ret
	
test_c:
	cmp ah, 0x2E
	jne .end
	; rerunning the video mode setup will clear the screen, so do that.
	jmp start
.end:
	ret

; ----
xpos dw 320
ypos dw 240
color db 0x0F
prev_color db 0
drawing db 1

times 510 - ($-$$) nop
db 0x55, 0xAA

; comment this to build a bootsector instead of a whole disk image.
times (1440*1024) - 512 db 0
