*****************************************************************
* Application: 	DTMF codec
* File:		sqrt.asm
* Description:	Square root estimation for normalization
*		
* History:
* Date		Who		Comment
* 07-28-97	Gunter Schmer	creation
*
*****************************************************************

*************************************************************************
* Function: 	void sqrt(int x)	--> A4 arg1
*					    B3 retaddr
*
* Description:	This function estimates a square root of a positive Q30
*		number x. The result is in Q15 format. This function is 
*		used for the normalization of input data.
*
* Pseudo C-code:
*
*	short sqrt(int x)
*	{
*		short y,delta;
*
*		for(i=0;i<15;i++)	{
*			delta = delta>>1;
*			error = y*y - x
*			if(error>0)	y = y - delta;
*			else		y = y + delta;
*		}
*		return(y);
*	}
*
* Regs used:	A1,A3,A4,A5,A6,A7,A8
*		B0,B3
*
* Regs modified:A1,A3,A4,A5,A6,A7,A8
*		B0
*
* Execution:	82 cycles
*
*************************************************************************
		.global	_sqrt
		.text
_sqrt:

;
;------ Register Allocation for sqrt loop ------------------------
;	A0 : 		A4 : x		A8 : 
;	A1 : cond	A5 : y		A9 : 
;	A2 : 0		A6 : delta	A10: 
;	A3 : y2		A7 : error	A11: 
;
;	B0 : count	B4 : 		B8 : 
;	B1 : 		B5 : 		B9 : 
;	B2 : 		B6 : 		B10:
;	B3 : ret addr	B7 : 		B11:
;
;	B14: DP
;	B15: SP
;
	MVK	.S1	4000h,A5	;initialize y = 0.5(Q15)
||	MVK	.S2	14,B0		;initialize loop count = 15
||	ZERO	.L1	A2		;initialize (A2)=0

	MVK	.S1	4000h,A6	;initialize delta = 0.5(Q15)
|| [B0] B	.S2	loop		;branch to loop

loop:
	MPY	.M1	A5,A5,A3	;y2=y*y

	SHR	.S1	A6,1,A6		;delta=delta>>1

	SUB	.L1	A3,A4,A7	;error = y*y - x

	CMPGT	.L1	A7,A2,A1	;(error>0)? --> A0
|| [B0]	SUB	.L2	B0,1,B0		;decrement loop count

   [A1] SUB	.S1	A5,A6,A5	;if(error>0) 	y=y-delta
|| [!A1]ADD	.L1	A5,A6,A5	;else		y=y+delta
|| [B0] B	.S2	loop		;branch to loop


	B	.S2	B3		;return
	MV	.S1	A5,A4		;return value y
	NOP		4

