/****************************************************************************/
/*	Copyright (c) 2009, Bendor Research Pty. Ltd. All rights reserved.		*/
/*	This software is released under the GNU General Public License, version	*/
/*	3, with the exemptions that 1) the header files installed by this 	 	*/
/*	package can be included in closed-source code and 2) the libraries		*/
/*	built by this package can be statically linked into a closed-source 	*/
/*	binary. See the file LICENSE for the details.							*/
/*	This software is provided "AS IS", without any warranty or guarantee.	*/
/*	By using this software you acknowledge that neither Bendor Research nor	*/
/*	any of its personnel or affiliates can be held liable for any damages,	*/
/*	including, but not limited to, loss of business, loss of money, loss of */
/*	life, loss of reputation, arising out of this software being faulty or	*/
/*	not performing as advertised, even if Bendor Research was aware of such	*/
/*	faults in the software. You use this software at your own risk, any and */
/*	all liabilities that arise out of your using this software are strictly	*/
/*	yours.																	*/
/****************************************************************************/

#include <math.h>
#include <libm.h>

/****************************************************************************/
/*					Local definitions										*/
/****************************************************************************/

#define	PI2		1.570796326794896619256404479703093102216

/****************************************************************************/
/*					Public API functions									*/
/****************************************************************************/

/** @addtogroup func */
/** @{ */

/**
*	Quadrant correct arcus tangent function.
*
*	The function returns the angle between the positive x axis and the
*	hypothenuse of a triangle formed by the (0,0) (x,0) (x,y) points.
*	The returned angle is in [-PI, +PI].
*
*	@param	x			The X coordinate of the end point of the hypothenuse
*	@param	y			The Y coordinate of the end point of the hypothenuse
*	@retval	NaN			Either x or y was NaN, they were both infinite or
*						they were both zero.
*	@retval	atan(y/x)	Otherwise; with the range extended to cover a full
*						circle, depending on the signum of y and x.
*/

double	atan2( double y, double x )
{
	if ( isnan( y ) || isnan( x ) ) return( nan( 0 ) );
	if ( isinf( y ) && isinf( x ) ) return( nan( 0 ) );
	if ( iszero( y ) && iszero( x ) ) return( nan( 0 ) );

	if ( iszero( y ) ) {

		if ( x > 0 )

			return( 0 );
		else
			return( 2 * PI2 );
	}

	if ( iszero( x ) ) {

		if ( y > 0 )

			return( PI2 );
		else
			return( -PI2 );
	}

	if ( x < 0 ) {

		x = atan( y / x );
		y = y < 0 ? -PI2 : +PI2;
		return( y - x );
	}
	else {

		return( atan( y / x ) );
	}
}

/** @} */

