;;
;; MAKE A BCD NUMBER FROM A BINARY NUMBER
;; 32 BIT BINARY NUMBER IN HL:BC, RESULT STORED AT (DE)
;; DE IS PRESERVED, ALL OTHER REGS DESTROYED
;;
;BIN2BCD:
;	PUSH	IX		; SAVE IX
;	PUSH	BC		; MOVE BC
;	POP	IX		; ... TO IX
;	LD	C,32		; LOOP FOR 32 BITS OF BINARY DWORD
;;
;BIN2BCD0:
;	; OUTER LOOP (ONCE FOR EACH BIT IN BINARY NUMBER)	
;	LD	B,5		; LOOP FOR 5 BYTES OF RESULT
;	PUSH	DE		; SAVE DE
;	ADD	IX,IX		; LEFT SHIFT NEXT BIT FROM HL:IX
;	ADC	HL,HL		; ... INTO CARRY
;;
;BIN2BCD1:
;	; INNER LOOP (ONCE FOR EACH BYTE OF BCD NUMBER)
;	LD	A,(DE)		; GET IT
;	ADC	A,A		; DOUBLE IT W/ CARRY
;	DAA			; DECIMAL ADJUST
;	LD	(DE),A		; SAVE IT
;	INC	DE		; POINT TO NEXT BCD BYTE
;	DJNZ	BIN2BCD1	; LOOP THRU ALL BCD BYTES
;;
;	; REMAINDER OF OUTER LOOP
;	POP	DE		; RECOVER DE
;	DEC	C		; DEC BIT COUNTER
;	JR	NZ,BIN2BCD0	; LOOP TILL DONE WITH ALL BITS
;	POP	IX		; RESTORE IX
;
; MAKE A BCD NUMBER FROM A BINARY NUMBER
; 32 BIT BINARY NUMBER IN DE:HL, RESULT STORED AT (BC)
; ON OUTPUT HL = BCD BUF ADR
;
BIN2BCD:
	PUSH	IX		; SAVE IX
	; CONVERT FROM DE:HL -> (BC) TO HL:IX -> (DE)
	; HL -> IX, DE -> HL, BC -> DE
	EX	DE,HL
	PUSH	DE
	POP	IX
	PUSH	BC
	POP	DE
;
	LD	C,32		; LOOP FOR 32 BITS OF BINARY DWORD
;
BIN2BCD0:
	; OUTER LOOP (ONCE FOR EACH BIT IN BINARY NUMBER)	
	LD	B,5		; LOOP FOR 5 BYTES OF RESULT
	PUSH	DE		; SAVE DE
	ADD	IX,IX		; LEFT SHIFT NEXT BIT FROM HL:IX
	ADC	HL,HL		; ... INTO CARRY
;
BIN2BCD1:
	; INNER LOOP (ONCE FOR EACH BYTE OF BCD NUMBER)
	LD	A,(DE)		; GET IT
	ADC	A,A		; DOUBLE IT W/ CARRY
	DAA			; DECIMAL ADJUST
	LD	(DE),A		; SAVE IT
	INC	DE		; POINT TO NEXT BCD BYTE
	DJNZ	BIN2BCD1	; LOOP THRU ALL BCD BYTES
;
	; REMAINDER OF OUTER LOOP
	POP	DE		; RECOVER DE
	DEC	C		; DEC BIT COUNTER
	JR	NZ,BIN2BCD0	; LOOP TILL DONE WITH ALL BITS
	EX	DE,HL		; HL -> BCD BUF
	POP	IX		; RESTORE IX
	RET
;
; PRINT CONTENTS OF 5 BYTE BCD NUMBER AT (HL)
; WITH LEADING ZERO SUPPRESSION
; ALL REGS DESTROYED
;
PRTBCD:
	INC	HL		; BUMP HL TO POINT TO
	INC	HL		; ...
	INC	HL		; ...
	INC	HL		; ... LAST BYTE OF BCD
	LD	B,5		; LOOP FOR 5 BYTES
	LD	C,0		; START BY SUPPRESSING LEADING ZEROES
;
PRTBCD1:
	; LOOP TO PRINT ONE BCD BYTE (TWO DIGITS)
	XOR	A		; CLEAR ACCUM
	RLD			; ROTATE FIRST NIBBLE INTO A
	CALL	PRTBCD2		; PRINT IT
	XOR	A		; CLEAR ACCUM
	RLD			; ROTATE SECOND NIBBLE INTO A
	CALL	PRTBCD2		; PRINT IT
	DEC	HL		; POINT TO PRIOR BYTE
	DJNZ	PRTBCD1		; LOOP TILL DONE
	RET			; RETURN
;
PRTBCD2:
	; SUBROUTINE TO PRINT A DIGIT IN A
	CP	C		; COMPARE INCOMING TO C
	RET	Z		; IF EQUAL, SUPPRESSING, ABORT
	DEC	C		; MAKE C NEGATIVE TO STOP SUPPRESSION
	ADD	A,'0'		; OFFSET TO PRINTABLE VALUE
	JP	COUT		; EXIT VIA CHARACTER OUT
