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

/**
*	Regular subtraction.
*
*	Subtract the topmost element from the element under it, discards
*	both and pushes the result onto the stack. Note that negative
*	numbers are not natural numbers, therefore if you want to subtract
*	a number from a smaller one, you will get an arror.
*
*	@param	nanu			The natural number machine state descriptor
*
*	@retval	BC_NANU_NANU	The operation succeeded
*	@retval	BC_NANU_SUND	There was less that 2 elements on the stack
*	@retval	BC_NANU_NANN	The result of the subtraction is not a natural
*							number (i.e. it is negative)
*	@retval	BC_NANU_OMEM	There's not enough memory in the pool to store
*							the result.
*
*	@par Stack image
*		b a ...  ==> a-b ...
*/

int		BC_NanuRsub( BC_NANU nanu )
{
int			va, vb, vr;
unsigned	sa, sb, of;
unsigned	*pa, *pb, *pr;

	if ( ( vb = _bc_NanuStkGet( nanu ) ) < 0 )

		return( _bc_NanuError( nanu, vb ) );

	if ( ( va = _bc_NanuStkGet( nanu ) ) < 0 )

		return( _bc_NanuError( nanu, va ) );

	sa = _bc_NanuVarLen( nanu, va );
	sb = _bc_NanuVarLen( nanu, vb );

	if ( sa > sb )

		return( _bc_NanuError( nanu, BC_NANU_NANN ) );

	if ( ( vr = _bc_NanuVarTmp( nanu, va, vb, sb ) ) < 0 )

		return( _bc_NanuError( nanu, vr ) );

	pa  = _bc_NanuVarPtr( nanu, va );
	pb  = _bc_NanuVarPtr( nanu, vb );
	pr  = _bc_NanuVarPtr( nanu, vr );
	of  = _bc_NanuSub2( pr, pa, pb, sb );
	pa += sb;
	pr += sb;
	sa -= sb;
	of  = _bc_NanuSub1( pr, pa, of, sa );

	if ( of )

		return( _bc_NanuError( nanu, BC_NANU_NANN ) );

	_bc_NanuVarDec( nanu, va );
	_bc_NanuVarDec( nanu, vb );
	_bc_NanuVarNrm( nanu, vr );
	_bc_NanuStkPut( nanu, vr );
	return( BC_NANU_NANU );
}

/** @} */


