/****************************************************************************/
/*	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>

/*
*	Cody-Waite range reduction
*	~~~~~~~~~~~~~~~~~~~~~~~~~~
*	This is a very simple reduction but faster than the Payne-Hanek one.
*	If the user chooses floats over doubles then precision is probably
*	secondary to speed and size, so the Cody-Waite is probably more suitable.
*	Since unlike Payne-Hanek the Cody-Waite reduction falls over if the
*	argument is too large, we limit the argument to +/- 1E8.
*	The original Cody-Waite reduction method uses two floats to represent
*	PI/4 to a high(er) precision. That way the reduction remains precise
*	to a range of +/- 256. Instead of that we transform the argument to
*	a double, which gives us 28 extra bits, more than enough to cover the
*	+/- 1E8 range.
*
*	This function takes an angle in radians and returns a number in [0,1)
*	that corresponds to the [0,PI/4) principal range of the argument. It
*	furthermore returns an octant, starting from 0, which tells you into
*	which PI/4 slice of the circle the argument falls. The argument's
*	absloute value is used for the calculations, its signum is simply
*	ignored.
*/

float	_blm_CodyWaite( float x, int *o )
{
double		t;
unsigned	n;

	x = fabsf( x );

	if ( isnan( x ) || x > +1e8f ) {

		*o = -1;
		return( nan( 0 ) );
	}

	t = (double) x * 1.27323954473516268615269908526244080349;
	n = t;
	*o = n & 7;
	return( (float) ( t - n ) );
}

