/****************************************************************************/
/*	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 addition.
*
*	Removes the topmost and second elements from the stack and pushes back the
*	sum of the two elements.
*
*	@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_OMEM	There's not enough memory in the pool to store
*							the result.
*
*	@par Stack image
*		a b ...  ==> a+b ...
*/

int		BC_NanuRadd( BC_NANU nanu )
{
int					var1, var2, vres;
unsigned int		*ptr1, *ptr2, *vptr;
unsigned int		siz1, siz2, temp;

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

		return( _bc_NanuError( nanu, var1 ) );

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

		return( _bc_NanuError( nanu, var2 ) );

	siz1 = _bc_NanuVarLen( nanu, var1 );
	siz2 = _bc_NanuVarLen( nanu, var2 );

	if ( siz1 < siz2 ) {

		vres = siz1;
		siz1 = siz2;
		siz2 = vres;
		vres = var1;
		var1 = var2;
		var2 = vres;
	}

	if ( ( vres = _bc_NanuVarTmp( nanu, var1, var2, siz1 + 1 ) ) < 0 )

		return( vres );

	ptr1  = _bc_NanuVarPtr( nanu, var1 );
	ptr2  = _bc_NanuVarPtr( nanu, var2 );
	vptr  = _bc_NanuVarPtr( nanu, vres );
	temp  = _bc_NanuAdd2( vptr, ptr1, ptr2, siz2 );
	ptr1 += siz2;
	vptr += siz2;
	siz1 -= siz2;
	temp  = _bc_NanuAdd1( vptr, ptr1, temp, siz1 );
	vptr += siz1;
	*vptr = temp;

	_bc_NanuVarDec( nanu, var1 );
	_bc_NanuVarDec( nanu, var2 );
	_bc_NanuVarNrm( nanu, vres );
	_bc_NanuStkPut( nanu, vres );
	return( BC_NANU_NANU );
}

/** @} */


