; 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:
	ld	a,h		; For reverse polarity subtraction
	or	l
	scf
	ret	z		; Division by zero; abort operation; carry set
	ld	a,b		; Put 2's complernent of BC +1 into DE for
	cpl			; Purposes of subtraction. (BC will be
	ld	d,a		; Incremented to enable subtraction when minuend
	ld	a,c		; And subtrahend are havinq equal values).
	cpl
	ld	e,a		; Dividend in negative form now in DE
	inc	bc		; BC +1; dividend incremented
	exx
	ld	hl,0		; Clear the quotient buffer
	exx			; (high-order part of quotient buffer)
	jr	double		; Start the division in earnest

;**********************  First phase: Doubling the divisor
restore:
	add	hl,bc		; Add back
double:
	inc	a		; Increment counter
	push	hl		; Save divisor
	add	hl,hl		; Double it, but go to second phase if
	jr	c,change	; HL now is larger than dividend in BC
	add	hl,de		; Comparison with dividend by subtraction
	jr	nc,restore	; Keep doubling unless HL now is larger than BC

;**********************  Second phase: Subtracting from the dividend
;			               and accumulating quotient bits.
change:
	ld	b,a		; Transfer count to new counter
subtrct:
	pop	hl		; Fetch halved divisor as positive subtrahend
	add	hl,de		; Subtract by using negative dividend as minuend
	jr	c,shiftc	; The carry bit becomes the quotient bit
	ex	de,hl		; Equivalent of adding back if subtraction fails
shiftc:
	ccf			; Invert quotient bit from reverse polarity
	exx
	rl	l		; Shift quotient bits
	rl	h
	exx
	djnz	subtrct		; Continue process until count-down finished
	exx
	push	hl
	exx
	pop	hl		; Place output quotient in HL.
	ld	a,e		; Change remainder in DE into proper polarity
	cpl
	ld	e,a
	ld	a,d
	cpl
	ld	d,a
	ret			; Division operation completed

	end

