/* void	Amortize(payintr,payprin,balance,intr,pv,pmt,begend,time)
 *
 * ARGUMENT
 *	DEC	*payintr,*payprin,*balance;
 *	DEC	*intr, *pv, *pmt;
 *	int	begend,	time;
 *
 * DESCRIPTION
 *	For a certain payment 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 payment 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.
 *
 * 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	Amortize(payintr,payprin,balance,intr,pv,pmt,begend,time)
DEC	*payintr,*payprin,*balance;
DEC	*intr, *pv, *pmt;
int	begend,	time;
{
	int	i;
	DEC	dnintr,	*nintr=&dnintr,	dnpmt, *npmt=&dnpmt;

	_MacStart(GM_AMORT);

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

	if (_MacBad(intr) || _MacBad(pv) || _MacBad(pmt))  {
		_MacErr(GM_INIT);
		_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);
	_MacDZero(payprin);
	(void) _ScaleDec80Bit(balance,pv,2);

	if (time==0)
		_MacRetV;

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

/* calculate rest of payments */
	for (i=2;i<=time;i++)  {
		(void) _MulDec80Bit(payintr, balance, nintr);
		(void) _ScaleDec80Bit(payintr,payintr,2);
		if (_MacIsDecN(payintr)^_MacIsDecN(npmt))
			_MacDChgs(payintr);
		(void) _SubDec80Bit(payprin, npmt, payintr);
		(void) _SubDec80Bit(balance, balance, payprin);
	}

	_MacRetV;
}