; Filename:     div32.s 
; Author:       ECE 353 Staff 
; Description:  Implementation of div32 function

	AREA    FLASH, CODE, READONLY
	ARM					;use ARM instruction set

	EXPORT  div32

; Name: div32 
; Description: Implementation of unsigned 32 bit division
; Assumes:     R0 - dividend
;              R1 - divisor
; Returns:     R0 - quotient 
;              R1 - remainder
; Modifies:    None
div32

	PUSH	{R2, R3, LR}		;context save

	MOVS	R2, R1				;test and store divisor
	MOVEQ	R0, #-1				;divide_by-0 error
	MOVEQ	R1, #-1				;divide_by-0 error
	BEQ		div32_exit
	MOV		R1, R0				;store dividend - will become remainder
	MOV		R0, #0				;clear quotient reg
	MOV		R3, #0				;clear shift count
; shift divisor left until first 1 in leftmost bit
div32_setup
	TST		R2, #0x80000000		;if already one in msb, don't shift
	BNE		div32_loop
	LSL		R2, #1				;shift divisor left one
	ADD		R3, R3, #1			;increment shift count
	B		div32_setup		
div32_loop
	LSL		R0, R0, #1			;shift quotient left with zero
	CMP		R1, R2				;is dividend >= divisor?
	BLO		div32_prep_next		;no - leave zero shifted in, continue	
	ORR		R0, R0, #1			;yes - change zero to 1
	SUB		R1, R1, R2			;subtract divisor from dividend
div32_prep_next
	LSR		R2, R2, #1			;shift divisor right one
	SUBS	R3, R3, #1			;decrement shift count remaining
	BPL		div32_loop			;loop until count neg.
div32_exit
	POP		{R2, R3, PC}		;context restore/return


	END
