
	;;
	;; Display MODE R example
	;;
	;; Developed on WinAPE assembler
	;;

	LET	SAVE_DSK = 0		;; to save example on DSK

	RUN	start

	NOLIST

	IF 	SAVE_DSK
		WRITE DIRECT "A:DMODER.BIN"
	ELSE
		WRITE DIRECT -1,-1,#c0
	ENDIF

	;; MACRO to wait cycles

	MACRO	WAIT_CYCLES _cycles

@loops		equ	_cycles-1/4
@loopsx4	equ	@loops*4
@nops		equ	_cycles-@loopsx4-1

	ld	b,@loops
@change_waitLoop
	djnz	@change_waitLoop

	defs	@nops,0

	MEND

	ORG	&8000
start
	di

	ld	bc,&7f8c + 0		;; set scr mode 0
	out	(c),c

	ld	hl,palette		;; set scr palette
	call	setPalette

mainLoop
	call	wVb

	ld	bc,&bc0c		;; video page switch (#c000 / #4000)
	out	(c),c
	inc	b
	ld	a,(CRTCReg12)
	out	(c),a
	xor	&20
	ld	(CRTCReg12),a

	ld	a,(topScanlines)	;; wait scanlines
	ld	c,a
	xor	1
	ld	(topScanlines),a
	ld	b,0	
	call	waitScanlines

	WAIT_CYCLES	34

	ld	bc,#bc02		;; select CRTC reg 2
	out	(c),c

	ld	d,222/2
rasterLoop
	ld	bc,#bd2d
	out	(c),c

	WAIT_CYCLES	64-7

	ld	bc,#bd2f
	out	(c),c

	WAIT_CYCLES	64-7-4

	dec	d
	jr	nz, rasterLoop

	jr	mainLoop

	;; Set Palette

setPalette
	xor	a
	ld	bc,#7f11
setPalette_loop
	out	(c),a
	inc	b
	outi
	inc	a
	cp	c
	jr	nz,setPalette_loop
	ret

	;; Wait vertical blank

wVb
	ld 	b,#f5
vbLoop1
	in 	a,(c)
        rra
        jr 	c, vbLoop1
vbLoop2
	in 	a,(c)
        rra
        jr 	nc, vbLoop2
	ret

	;; Wait BC scanlines
	
waitScanlines
	ld	a,b				; 1c
	or	c				; 1c
	ret	z				; 2/4c

	push	bc				; 4c
	WAIT_CYCLES 	40
	pop	bc				; 3c
	dec	bc				; 2c
	ld	a,b				; 1c
	or	c				; 1c
	ret	z				; 2/4c
						; 	57c
waitScanlines_loop
	push	bc				; 4c
	WAIT_CYCLES 	50
	pop	bc				; 3c
	dec	bc				; 2c
	ld	a,b				; 1c
	or	c				; 1c
	jr	nz, waitScanlines_loop		; 2/3c

	ret					; 3c

	;; Data

topScanlines	db	51
CRTCReg12	db	&30
palette		db 	&54, &44, &55, &5c, &4c, &46, &57, &5e, &40, &5f, &4e, &47, &5a, &5b, &4a, &4b
border		db	&54

	;; Screen

	IF 	SAVE_DSK
		WRITE DIRECT "A:BF320.RWE"
	ENDIF

	ORG	&4000

	incbin "bf320.rwe"		;; even screen frame

	IF 	SAVE_DSK
		WRITE DIRECT "A:BF320.RWO"
	ENDIF

	ORG	&c000

	incbin "bf320.rwo"		;; odd screen frame
