; mailmath/asm - kjw/bqsd - version 2.00 - 01/83
;
	SUBTTL	'<mailmath/asm - 24 bit math subs>'
;
	PAGE
;
;	compare BHL <> CDE
;	C = BHL < CDE
;	Z = BHL = CDE
;	NC= BHL >= CDE
;
CMPBHL	LD	A,B		;get MSB
	CP	C		;compare
	RET	NZ		;go if not equal
	LD	A,H		;get NSB
	CP	D		;compare
	RET	NZ		;go if not equal
	LD	A,L		;get LSB
	CP	E		;compare
	RET			;return with Z,C,NC flags
;
;	increment BHL (BHL = BHL + 1)
;
INCBHL	INC	L		;bump LSB
	RET	NZ		;not FF => 00
	INC	H		;bump NSB
	RET	NZ		;not FF => 00
	INC	B		;bump MSB
	RET			;BHL = BHL +1
;
;	decrement BHL (BHL = BHL - 1)
;
DECBHL	LD	A,-1		;load FF
	DEC	L		;dec LSB
	CP	L		;overflow?
	RET	NZ		;not 00 => FF
	DEC	H		;dec NSB
	CP	H		;overflow?
	RET	NZ		;not 00 => FF
	DEC	B		;dec MSB
	RET			;BHL = BHL -1
;
;	triple precision multiply (BHLA = BHL * A)
;
TMULT	PUSH	IX		;save
	PUSH	DE		;save
;
	PUSH	BC		;save
	LD	C,B		;pass MSB
	EX	DE,HL		;CDE = multiplicand
	LD	HL,0		;init result MSB's
	LD	IX,0		;init result LSB's
	LD	B,8		;multiplier precision
;
TMULT1	ADD	IX,IX		;shift result left
	ADC	HL,HL		;shift result left
	RLCA			;1 bit?
	JR	NC,TMULT2	;go if not
	PUSH	BC		;save
	ADD	IX,DE		;result + multiplicand
	LD	B,0		;init
	ADC	HL,BC		;catch overflow
	POP	BC		;unstack
;
TMULT2	DJNZ	TMULT1		;go for precision
	PUSH	IX		;pass back to DE
	POP	DE		;DE = result LSB's
	LD	A,E		;A = result LSB
	POP	BC		;unstack
	LD	B,H		;B = MSB
	LD	H,L		;H = NSB
	LD	L,D		;L = LSB
;
	POP	DE		;unstack
	POP	IX		;unstack
	RET			;done
;
;	triple precision divide (BHL:A = BHL / A)
;
TDIVD	PUSH	DE		;save it
	LD	D,A		;D = divisor
	LD	E,24		;dividend precision
	XOR	A		;init lsb bits
;
TDIVD1	ADD	HL,HL		;shift dividend left
	RL	B		;shift dividend left
	RLA			;shift low 8 bits
	JR	C,TDIVD2	;go if overflow
	CP	D		;at divisor?
	JR	C,TDIVD3	;go if yes
;
TDIVD2	SUB	D		;remainder - divisor
	INC	L		;quotient +1
;
TDIVD3	DEC	E		;less precision
	JR	NZ,TDIVD1	;go till done
	POP	DE		;unstack
	RET			;BHL = result
;
;	subtract CDE from BHL (BHL = BHL - CDE)
;
SUBIT	LD	A,L		;fetch LSB
	SUB	E		;less LSB
	LD	L,A		;update
	LD	A,H		;fetch NSB
	SBC	A,D		;less NSB
	LD	H,A		;update
	LD	A,B		;fetch MSB
	SBC	A,C		;less MSB
	LD	B,A		;update
	RET			;BHL = result
;
;	add CDE to BHL (BHL = BHL + CDE)
;
ADDIT	LD	A,L		;fetch LSB
	ADD	A,E		;add LSB
	LD	L,A		;update
	LD	A,H		;fetch NSB
	ADC	A,D		;add NSB
	LD	H,A		;update
	LD	A,B		;fetch MSB
	ADC	A,C		;add MSB
	LD	B,A		;update
	RET			;done, BHL = result
;
