//****************************************************************************************
//                                                                                       *
//   R8C Program Collection No. 12                                                       *
//   CPU        : R8C/Tiny                                                               *
//                                                                                       *
//****************************************************************************************


//========================================================================================
//	Title: Dividing 32 bits
//	Outline: Divides 32-bit data together using registers
//	Input:	------------------------------>	Output:
//	R0 (Lower half of dividend)				R0 (Lower half of quotient)
//	R1 (Lower half of divisor)				R1 (Lower half of divisor)
//	R2 (Upper half of dividend) 			R2 (Upper half of quotient)
//	R3 (Upper half of divisor)				R3 (Upper half of divisor)
//	A0 ( )									A0 (Lower half of remainder)
//	A1 ( )									A1 (Upper half of remainder)
//	Stack amount used: 3 bytes
//	Notes: R2R0 / R3R1 
//	       Division by zero is returned by Z flag.
//========================================================================================

.text 
.global	_DIVIDE32 
.type	_DIVIDE32, @function

#pragma inline_asm(_DIVIDE32)
_DIVIDE32:											 
	ENTER	#1										// Sets stack frame
    .equ	CNT,		-1							// Shift count counter

	MOV.B	#0,a0									// Initializes remainder area
	MOV.B	#0,a1									// 
	CMP.W	#0,r1									// 
	JNE		DIVIDE32_10								// 
	CMP.W	#0,r3									// 
	JEQ		DIVIDE32exit							// --> Division by zero
DIVIDE32_10:										// 
	MOV.B	#32,CNT[FB]								// Sets number of shifts performed (32 times)
DIVIDE32_20:										// 
	SHL.W	#1,r0									// Pushes dividend and carry quotient
	ROLC.W	r2										// 
	ROLC.W	a0										// Creates dividend
	ROLC.W	a1										// 
	SUB.W	r1,a0									// Subtracts divisor
	SBB.W	r3,a1									// 
	BMC		0,r0									// Sets quotient
	JC		DIVIDE32_30								// --> Subtraction of divisor succeeded
	ADD.W	r1,a0									// Restored to original data because subtraction of divisor failed
	ADC.W	r3,a1									// 
DIVIDE32_30:										// 
	ADJNZ.B	#-1,CNT[FB],DIVIDE32_20					// --> Executes next digit
	FCLR	Z										// Division succeeded
DIVIDE32exit:										// 
	EXITD											// Clears stack frame


.END
