.entry_point
	di
	
	ld SP,stack
	
;interrupt returns
	ld HL,#C9FB
	ld (#38),HL	

;CRTC
	ld HL,crtc_config
	call GFX_SetCRTC
;mode 1
	ld BC,#7F8C+1
	out (C),C	
;colors
	ld BC,#7F00	
	out (C),C		;4nops
	ld A,#54
	out (C),A
	ld C,16
	out (C),C
	out (C),A
	
;bg
	call GFX_Cls
	call draw_image


.restart
;break
	ld SP,stack
.wait_vbl
	ld B,#F5
	in	A,(C)
	rra
	jr nc,wait_vbl
	
	ei
	halt
	halt
	
	ld BC,#7F03		;4nops
	ld A,1			;2nops
	
	ds 42,0			;42 ;synchro to first line
	
	
	di
	
	ld SP,line_table
	ret
	
.end_of_lines
	ld SP,stack

	;call Check_key
	;jr z,restart
	
	;ld BC,#BC01
	;xor A
	;out (C),C
	;inc B
	;out (C),A
	
	;rst 0
	jr restart
	


.crtc_config
	db #01,0,#02,#2A,4,#26,5,0,#06,20,#07,29,#0C,#30,#0D,#00,9,7,#FF
	
GFX_Cls:
	ld HL,#C000
	xor A
	ld (HL),A
	ld E,L
	ld D,H
	inc DE
	ld BC,#3FFF
	ldir
	ret
	
;setup crtc
; HL = setup data (reg,data) ending with #FF
GFX_SetCRTC:

	ld B,#BC
	ld A,#FF
.CRTC_loop
	ld C,(HL)
	cp C
	ret z

	out (C),C
	inc B
	inc HL

	ld C,(HL)
	out (C),C
	dec B
	inc HL

	jr CRTC_loop
	
.draw_image
	ld HL,image
	ld DE,#C001
	ld B,26
.draw_image_char
	push BC
	push DE
.draw_image_line
	ld B,8
.draw_image_byte
	push BC
	push DE
	ld BC,64
	ldir
	pop DE
	ld A,8
	add D
	ld D,A
	pop BC
	djnz draw_image_byte
	pop DE
	ex DE,HL
	ld BC,64+2
	add HL,BC
	ex DE,HL
	pop BC
	djnz draw_image_char
	ret
	
; keyboard funcs

.Scan_key
        ld hl,keymap    ;3
        ld bc,#f782     ;3
        out (c),c       ;4
        ld bc,#f40e     ;3
        ld e,b          ;1
        out (c),c       ;4
        ld bc,#f6c0     ;3
        ld d,b          ;1
        out (c),c       ;4
        ld c,0          ;2
        out (c),c       ;4
        ld bc,#f792     ;3
        out (c),c       ;4
        ld a,#40        ;2
        ld c,#4a        ;2 44
.scan_loop    
	ld b,d          ;1
        out (c),a       ;4 select line
        ld b,e          ;1
        ini             ;5 read bits and write into KEYMAP
        inc a           ;1
        cp c            ;1
        jr c,scan_loop       ;2/3 9*16+1*15=159
        ld bc,#f782     ;3
        out (c),c       ;4
        ret

.keymap
	ds 10,0

.Check_key
	call Scan_key

	ld HL,keymap
	ld B,10
	ld C,0

.Check_key_loop
	ld A,(HL)
	xor #FF
	or C
	ld C,A
	inc HL
	djnz Check_key_loop

	ld A,C
	or A
	ret

read "128konly_lines_table.asm"
read "128konly_lines.asm"

	ds 256,0
.stack
	
.image
	incbin "gfx/128konly.pm1"
