; bml.a

	.bext scanconvert
	.bext xtoxd

	.srel
scanconvert:
	.scanconvert
xtoxd:
	.xtoxd
	.nrel

; -----------------------
; S C A N   C O N V E R T
; -----------------------

; pidNwrds = 0
; pidBi = 1
; pidPwBase = 2
; pidXb = 3
; pidFont = 4
; pidRgfinfo = 5
; pidRgxw = 6

.scanconvert:		; cr in ac0; cvt in ac1

	inc 3 3
	sta 3 rtnScan
	sta 2 fm		; save caller's frame ptr
	mov 1 2		; cvt in ac2

; pfinfo ← rgfinfo + cr

	lda 3 5 2		; pidRgfinfo
	add 0 3
	sta 3 pfinfo

; pdx ← rgxw + cr

	lda 3 6 2		; pidRgxw
	add 0 3
	sta 3 pdx

; do

	lda 0 3 2		; pidXb

chloop:			; xb in ac0

; bi ← (~xb) & 17B

	com 0 3		; ~xb in ac3
	lda 1 oct17
	and 1 3		; bi in ac3
	sta 3 1 2		; pidBi

; pw ← pwBase + xb/16

	com 1 1		; 177760B
	and 1 0		; clear last 4 bits
	cycle 14		; shift right 4 (unsigned)
	lda 3 2 2		; pidPwBase
	add 3 0

; ch ← (rv pfinfo).char

	lda 3 @pfinfo
	lda 1 chmask
	and 1 3

extloop:

; if convert[ac0: pw, ac3: font + ch] then goto extcode

	lda 1 4 2		; pidFont
	add 1 3
	convert 0		; pidNwrds
	jmp extcode	; convert skips if no ext needed

; xb ← xb + (rv pdx)/40B

	lda 0 @pdx
	lda 1 oct177740
	and 1 0		; clear last 5 bits
	movl# 0 0 szc	; skip if ge 0
	adc 1 0		; set same bits
	cycle 13		; i.e. right 5; ac0 now holds dx/40B (signed)
	lda 1 3 2		; pidXb
	add 1 0
	sta 0 3 2		; pidXb

; pfinfo ← pfinfo + 1
; pdx ← pdx + 1

	isz pfinfo
	isz pdx

; if (rv pfinfo).flags eq 0 then loop

	lda 3 @pfinfo
	lda 1 finfomask
	and# 3 1 snr	; skip if nonzero
	jmp chloop

; return cr ← pfinfo - rgfinfo

	lda 0 pfinfo
	lda 3 5 2		; pidRgfinfo
	sub 3 0		; cr now in ac0
	lda 2 fm
	jmp @rtnScan

extcode:			; pw still in ac1, chExt in ac3

; pw ← pw + 1

	inc 0 0

; loop

	jmp extloop


rtnScan:	0
fm:		0
pfinfo:	0
pdx:		0

chmask:	377
finfomask:	137000	; everything but space and fNoCk
oct177740:	177740
oct17:	17


; -----------------------
; X   T O   X D
; -----------------------

.xtoxd:			; x in ac0

	lda 1 oct177740
	and 1 0		; clear last 5 bits
	movl# 0 0 szc	; skip if ge 0
	adc 1 0		; set same bits
	cycle 13		; i.e. right 5; ac0 now holds x/40B (signed)
	jmp 1 3