; TODO: Optimization possible

	zpage	btmp0
	zpage	btmp1
	zpage	r0
	zpage	r1
	zpage	r28
	zpage	r29
	zpage	r30
	zpage	r31

	global	__fmemcpy
	global	___bankcopy
	global	___bankcopy_len
	section	text
___bankcopy:
	stx	savex
	ldx	#7
l1:
	lda	btmp0,x
	sta	saveb,x
	dex
	bne	l1
	ldx	savex
        lda     r28
        sta     btmp1
        lda     r29
        sta     btmp1+1
        sty     btmp1+2
        lda     r30
        sta     btmp0
        lda     r31
        sta     btmp0+1
        stx     btmp0+2
        lda     ___bankcopy_len
	sta	r0
        lda     ___bankcopy_len+1
	sta	r1
	jsr	__fmemcpy
	ldx	#7
l2:
	lda	saveb,x
	sta	btmp0,x
	dex
	bne	l2
	ldx	savex
	rts

__fmemcpy:
	phz
	ldx	r0
	ldy	r1
        ldz     #0
        stz     btmp0+3
        stz     btmp1+3
	inc	btmp0+2
	bne	banked1
	inc	btmp0+2
banked1:
	inc	btmp0+2
	lsr	btmp0+2
	bcc	skip1
	smb6	btmp0+1
skip1:
	lsr	btmp0+2
	bcs	skip2
	rmb7	btmp0+1
skip2:
	inc	btmp1+2
	bne	banked2
	inc	btmp1+2
banked2:
	inc	btmp1+2
	lsr	btmp1+2
	bcc	skip3
	smb6	btmp1+1
skip3:
	lsr	btmp1+2
	bcs	loop
	rmb7	btmp1+1
loop:
	lda	[btmp1],z
	sta	[btmp0],z
	inw	btmp0
	inw	btmp1
	cpx	#0
	bne	skip
	dey
skip:
	dex
	bne	loop
	cpy	#0
	bne	loop
	plz
	rts

	section	bss
___bankcopy_len:
	reserve	2
savex:
	reserve	1
saveb:
	reserve	8

