; division  program  DIVIDE

;input dividend in BC and input divisor in HL.
;output quotient in HL and output remainder in DE.
;carry set if division by zero

;**********************  Test for division by zero and prepare
DIVIDE:	mov	a,h	;for reverse polarity subtraction
	ora	l
	stc
	rz		;division by zero; abort operation; carry set
	mov	a,b	;put 2's complernent of BC +1 into DE for
	cma		;purposes of subtraction. (BC will be
	mov	d,a	;incremented to enable subtraction when minuend
	mov	a,c	;and subtrahend are havinq equal values).
	cma
	mov	e,a	;dividend in negative form now in DE
	inx	b	;BC +1; dividend incremented
	xra	a	;reset counter A and
	sta	quot	;clear the quotient buffer
	sta	quot+1	;(high-order part of quotient buffer)
	jmp	double	;start the division in earnest

;**********************  First phase: Doubling the divisor
restore:dad	b	;add back
double: inr	a	;increment counter
	push	h	;save divisor
	dad	h	;double it, but go to second phase if
	jc	change	;HL now is larger than dividend in BC
	dad	d	;comparison with dividend by subtraction
	jnc	restore	;keep doubling unless HL now is larger than BC

;**********************  Second phase: Subtracting from the dividend
;			               and accumulating quotient bits.
change:	mov	b,a	;transfer count to new counter
subtrct:pop	h	;fetch halved divisor as positive subtrahend
	dad	d	;subtract by using negative dividend as minuend
	jc	shiftc	;the carry bit becomes the quotient bit
	xchg		;equivalent of adding back if subtraction fails
shiftc:	cmc		;invert quotient bit from reverse polarity
	lda	quot	;shift quotient bits
	ral
	sta	quot	;and place into temporary storage
	lda	quot+1
	ral
	sta	quot+1
	dcr	b	;count-down finished?
	jnz	subtrct	;no, continue process
	lhld	quot	;yes, place output quotient in HL.
	mov	a,e	;change remainder in DE into proper polarity
	cma
	mov	e,a
	mov	a,d
	cma	
	mov	d,a
	ret		;division operation completed

quot:	ds	2	;buffer for evolving quotient

