/* void	AmortizeTable(payintr,payprin,balance,intr,pv,pmt,begend,time)
 *
 * ARGUMENT
 *	DEC	**payintr, **payprin, **balance;
 *	DEC	*intr, *pv, *pmt;
 *	int	begend,	time;
 *
 * DESCRIPTION
 *	For several payments of	a loan,	computes the amount of the payment
 *   applied towards interest (payintr), the amount of the payment applied
 *   towards principle (payprin), and the remaining balance (balance).	The
 *   loan is described by its present value (pv), the payment (pmt), the
 *   interest rate (intr), and whether payments	are at the beginning or	end
 *   of	the month (begend), while time tells the number	of payments for	which
 *   the calculations should be	done.  pv should be positive while pmt should
 *   be	negative to obey the sign convention.  The output is rounded to	two
 *   decimal places.  The results are stored in	3 arrays.
 *
 * SIDE	EFFECTS
 *	None.
 *
 * RETURNS
 *	None.
 *
 * POSSIBLE ERRORS
 *	GM_NULLPOINTER
 *	GM_ARGVAL
 *
 * AUTHOR
 *  Jared Levy
 *   Copyright (C) 1988-1990 Greenleaf Software	Inc.  All rights reserved.
 *
 * MODIFICATIONS
 *
 *
 */

#include <stdio.h>
#include "gm.h"
#include "gmsystem.h"

void	AmortizeTable(payintr,payprin,balance,intr,pv,pmt,begend,time)
DEC	**payintr, **payprin, **balance;
DEC	*intr, *pv, *pmt;
int	begend,	time;
{
	int	i, n1, n2;
	DEC	dnintr,	*nintr=&dnintr,	dnpmt, *npmt=&dnpmt;

	_MacStart(GM_AMORTTBL);

	if (!payintr||!payprin||!balance||!intr||!pv||!pmt)  {
		_MacErr(GM_NULLPOINTER);
		_MacRetV;
	}

	if (_MacBad(intr) || _MacBad(pv) || _MacBad(pmt))  {
		_MacErr(GM_INIT);
		_MacRetV;
	}

	for (i=0;i<=time;i++)
		if (!payintr[i]||!payprin[i]||!balance[i])  {
			_MacErr(GM_NULLPOINTER);
			_MacRetV;
		}

	if ((begend!=GM_BEGIN&&begend!=GM_END)||time<0)	 {
		_MacErr(GM_ARGVAL);
		_MacRetV;
	}

	_MacDCopy(nintr, intr);
	nintr->dc.id+=2;
	_ScaleDec80Bit(npmt,pmt,2);

/* store results for payment '0' */
	_MacDZero(payintr[0]);
	_MacDZero(payprin[0]);
	(void) _ScaleDec80Bit(balance[0],pv,2);

	if (time==0)
		_MacRetV;

/* calculate payment 1 results */
	if (begend!=GM_BEGIN)  {
		(void) _MulDec80Bit(payintr[1],	balance[0], nintr);
		(void) _ScaleDec80Bit(payintr[1], payintr[1] ,2);
		if (_MacIsDecN(payintr[1])^_MacIsDecN(npmt))
			_MacDChgs(payintr[1]);
	}
	else
		_MacDZero(payintr[1]);
	(void) _SubDec80Bit(payprin[1],	npmt, payintr[1]);
	(void) _SubDec80Bit(balance[1],	balance[0], payprin[1]);

/* calculate rest of payments */
	for (i=2;i<=time;i++)  {
		(void) _MulDec80Bit(payintr[i],	balance[i-1], nintr);
		(void) _ScaleDec80Bit(payintr[i],payintr[i],2);
/* for some reason, this routine failed	when the _MacIsDecN & the ^ are	*/
/* on the same line as the if */
		n1 = _MacIsDecN(payintr[i]);
		n2 = _MacIsDecN(npmt);
		if (n1 ^ n2)
			_MacDChgs(payintr[i]);
		(void) _SubDec80Bit(payprin[i],	npmt, payintr[i]);
		(void) _SubDec80Bit(balance[i],	balance[i-1], payprin[i]);
	}

	_MacRetV;
}