/****************************************************************************/
/*	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 or 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 <nanu-nanu.h>

/** @addtogroup nanu */
/** @{ */

/**
*	Number of trailing 0 bits of a number.
*
*	Returns the number of trailing zero bits of the number on the
*	top of the stack. For example, if the number on the top of the stack
*	is 11552, which is binary 10110100100000, the function will return 5.
*	If the number on the top of the stack is 0, then the function returns
*	the largest positive signed int, i.e. 0x7fffffff (MAX_INT).
*
*	@param	nanu			The natural number machine state descriptor
*
*	@retval	BC_NANU_SUND	The stack was empty
*	@retval	0x7fffffff		The number on the top of the stack is 0
*	@retval	>=0				The number of trailing 0 bits in the number
*
*	@par Stack image
*		a ...  ==> a ...
*/

int		BC_NanuTail( BC_NANU nanu )
{
int			v;
unsigned	n;
unsigned	*p;

	if ( ( v = _bc_NanuStkSee( nanu, 0 ) ) < 0 )

		return( _bc_NanuError( nanu, v ) );

	n = 0;
	p = _bc_NanuVarPtr( nanu, v );
	if ( _bc_NanuVarLen( nanu, v ) == 1 && ! *p ) return( 0x7fffffff );
	for ( n = 0 ; ! *p ; n++, p++ );
	for ( n <<= 5, v = *p ; ! ( v & 1 ) ; v >>= 1, n++ );
	return( n );
}

/** @} */

