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

/**
*	Splits a double number to a double mantissa and an integer exponent.
*
*	The function decomposes its first argument \p x to a pair of a float-point
*	\p m and an integer \p e so that the following is true:<br><br>
*	<tt>x = m * 2<sup>e</sup></tt><br>
*	<tt>0.5 <= |m| < 1.0</tt><br><br>
*	Them it stores \p e by the location pointed by the second argument and
*	return \p m.
*
*	@param	x		The double that should be split
*	@param	p		Pointer to an integer that will hold the exponent
*
*	@retval	NaN				if the argument was NaN, *p is set to 0x80000000
*	@retval	INF				if the argument was infinite, *p is set 0x7fffffff
*	@retval	0				if the argument was zero, *p is set to 0
*	@retval	+/-[0.5,1.0)	otherwise, *p is set so that <i>return value *
*							2<sup>*p</sup></i> is the argument x.
*/

double	frexp( double x, int *p )
{
unsigned long long	n;
int					e, s;

	if ( isnan( x ) ) {

		*p = 0x80000000;
		return( x );
	}

	if ( isinf( x ) ) {

		*p = 0x7fffffff;
		return( x );
	}

	if ( x == 0 ) {

		*p = 0;
		return( x );
	}

	n = _blm_dtoull( x );
	s = n >> 63;
	e = ( n >> 52 ) & 0x7ff;
	n = n & 0x000fffffffffffffull;

	if ( ! e ) {

		while ( ! ( n & ( 1ull << 52 ) ) ) {

			n <<= 1;
			e--;
		}

		n &= ~( 1ull << 52 );
	}

	n |= (unsigned long long) s << 63;
	n |= 0x3feull << 52;
	*p = e - 1022;
	return( _blm_ulltod( n ) );
}

/** @} */

