	.Z80
	ENTRY DIVBC
DIVBC:	;divides the 16-bit integer in DE by the 16-bit integer in HL.
	;Returns the quotient in DE, the residuum in BC, and the
	;divisor in HL.
	LD A,H		;check divisor
	OR L		;if it's zero return with A=0 (otherwise A=FFH)
	RET Z
	PUSH HL		;save divisor
	LD B,0
	LD C,B
	SCF		;dividend < divisor ?
	SBC HL,DE
	JP NC,DIVBC8
	POP HL
	PUSH HL
	XOR A		;init shift count
DIVBC1:	PUSH HL		;align divisor to dividend
	SCF
	CCF
	SBC HL,DE
	POP HL
	JP Z,DIVBC3
	PUSH HL
	ADD HL,HL
	PUSH HL
	JP C,DIVBC2
	SCF
	SBC HL,DE
	JP NC,DIVBC2
	POP HL
	POP BC
	INC A
	JP DIVBC1
DIVBC2:	POP HL
	POP HL
DIVBC3:	PUSH HL
	LD B,0		;quotient = 0
	LD C,B
	LD (DIVBCA),A	;save shift count
DIVBC4:	EX DE,HL	;repeat subtractions
	SCF
	CCF
	SBC HL,DE
	EX DE,HL
	INC BC
DIVBC5:	OR A
	JP Z,DIVBC6	;no more shifts
	DEC A
	LD H,B
	LD L,C
	ADD HL,HL
	LD B,H
	LD C,L
	EX DE,HL
	ADD HL,HL
	EX DE,HL
	POP HL
	PUSH HL
	SCF
	SBC HL,DE
	POP HL
	PUSH HL
	JP NC,DIVBC5
	JP DIVBC4
DIVBC6:	POP HL		;throw away shifted divisor
	LD A,(DIVBCA)	;get shift count and
DIVBC7:	OR A
	JP Z,DIVBC8
	DEC A		;shift residuum to right hand end
	SRL E
	SRL D
	JP NC,DIVBC7
	SET 7,E
	JP DIVBC7

DIVBC8:	LD H,B		;load registers with output values
	LD L,C
	EX DE,HL	;DE = quotient
	LD B,H
	LD C,L		;BC = residuum
	POP HL		;HL = divisor
	LD A,0FFH	;indicates "No error"
	RET
DIVBCA:	DB 0		;shift count

	END
