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

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

/** @addtogroup ieee */
/** @{ */

/**
*	Round a number to the nearest integer
*
*	The function returns a float that represents the integer
*	closest to its argument. If the fractional part of the argument
*	is exactly 0.5, then the integer further away from 0 is returned.

*	The argumen is returned unchanged if it was NaN or its absolute value
*	was larger than 2<sup>24</sup>; positive 0 is returned if the absolute
*	value of the argument was less than 0.5 and the rounding result is
*	returned otherwise.
*
*	@param	x		The number to be rounded
*	@return			The rounded value
*/

float	roundf( float x )
{
unsigned	m, e, s;

	m = _blm_ftoul( x );
	s = m >> 31;
	e = ( ( m >> 23 ) & 0xff );
	m = m & 0x007fffff;

	if ( e > 0x95 ) return( x );
	if ( e < 0x7e ) return( 0.0 );

	m  |= 1 << 23;
	m <<= 1;
	m >>= 0x96 - e;
	m  += 1;
	m >>= 1;
	m <<= 0x96 - e;

	if ( m & ( 1 << 24 ) ) {

		m >>= 1;
		e++;
	}

	m &= ~( 1 << 23 );
	m |= e << 23;
	m |= s << 31;
	return( _blm_ultof( m ) );
}

/** @} */

