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

/**
*	Rounds a number down to the nearest integer.
*
*	If the argument is infinite, NaN, zero or a value that represents an
*	integer, then the value is returned as it is. For all other values
*	the value representing the largest integer that is not larger than
*	the argument is returned. That is, for positive numbers the fractional
*	part is simply discarded, for negative numbers the fractional part
*	is discarded and 1 is subtracted from the number. E.g. 2.5 will change
*	to 2.0 but -2.5 will be changed to -3.0.
*
*	@param	x	The number to calculate the floor of
*
*	@return		The floor of x, or x if x is already an integer, is infinite,
*				is zero or is not a number.
*/

double	floor( double x )
{
unsigned long long	m;
unsigned int		r, e;

	m = _blm_dtoull( x );
	e = ( m >> 52 ) & 2047;
	r = 1075 - e;
	if ( e < 1023 ) return( (long long) m < 0 ? -1.0 : 0.0 );
	if ( e > 1075 ) return( x );
	if ( ( m & ( ( 1ull << r ) - 1 ) ) == 0 ) return( x );

	m >>= r;
	m <<= r;

	if ( (long long) m < 0 ) {

		m &= 0x000fffffffffffffull;
		m |= 1ull << 52;
		m += 1ull << r;

		if ( m & ( 1ull << 53 ) ) {

			m >>= 1;
			e++;
		}

		m &= ~( 1ull << 52 );
		m |= (unsigned long long) ( e | 0x800 ) << 52;
	}

	return( _blm_ulltod( m ) );
}

/** @} */

