; BCKid ADF reader - basically turr2 reader with different sizes
; based on BCKid.islave 1.0 (21.02.00) by Mr.Larmer

NO_INCLUDES=1
;MESSAGES=1
	include	adfreader.asm
	BUFFER	TRACKBUFFER

; track 0: dos track ($1600 bytes)
	WRITEDOS #0

; track 1: hiscores. either empty dos track (original disk), or 388 bytes
; encoded (disk after hiscores saved)
	lea	TRACKBUFFER,a0
	moveq	#(388/4)-1,d0
.clr	clr.l	(a0)+
	dbra	d0,.clr
	WRITE	#388

; tracks 2-159:
; - $9521 MFM sync
; - unused byte (encoded as 2 bytes MFM, always $2aaa)
; - 6500 bytes of data (stored as 1625 8-byte MFM encoded longwords)
; - longword checksum, which is XOR of all preceding raw MFM data, then
;   odd bits masked out (encoded as MFM long)

	moveq	#2,d7	; d7 = tracknumber
.nxttrk	RAWREAD	d7	; read track
	RESYNC	#$9521	; resync track

	lea	TRACKBUFFER,a0
	lea	2(a0),a1
	cmp.w	#122,d7		; track 122 / bckid.adf is very wrong
	beq.s	.nochk
	cmp.w	#$2aaa,(a1)+
	bne.s	.fail

.nochk	move.w	#(6500/4)-1,d0
	moveq	#0,d3		; accumulated checksum
	move.l	#$55555555,d4	; 0101010101010...
.decode	movem.l	(a1)+,d1/d2	; read 8-byte MFM encoded long
	eor.l	d1,d3		; checksum raw MFM data
	eor.l	d2,d3
	and.l	d4,d1		; decode MFM long
	and.l	d4,d2
	add.l	d1,d1
	or.l	d2,d1
	move.l	d1,(a0)+	; write long
	dbra	d0,.decode

	movem.l	(a1)+,d1/d2	; get stored checksum
	and.l	d4,d1		; decode
	and.l	d4,d2
	add.l	d1,d1
	or.l	d2,d1
	and.l	d4,d3		; mask odd bits out
	cmp.l	d1,d3		; verify checksum
	beq.s	.ok
	cmp.w	#159,d7		; track 159 has an intentional wrong checksum
	beq.s	.ok
	cmp.w	#122,d7		; track 122 / bckid.adf is very wrong
	beq.s	.ok

.fail	FAILURE	cksum(pc)

.ok	WRITE	#6500

	addq.w	#1,d7
	cmp.w	#160,d7
	bne.s	.nxttrk
	rts

cksum	dc.b	"bad checksum",0

