#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>


void Usage(void){
	printf("./loan [loan_balance] [interest_rate] [monthly_payment]\n");
}
/*
The following formula is used to calculate the fixed monthly payment (P) required to fully amortize a loan of L dollars over a term of n months at a monthly interest rate of c. [If the 
quoted rate is 6%, for example, c is .06/12 or .005]. 
P = L[c(1 + c)n]/[(1 + c)n - 1]

The next formula is used to calculate the remaining loan balance (B) of a fixed payment loan after p months.
B = L[(1 + c)n - (1 + c)p]/[(1 + c)n - 1]

 the amount owed every month equals the amount owed from the previous month plus interest on that amount, minus the fixed monthly payment;
*/
int main(int argc, char **argv){
	double loan_balance = 0;
	double loan_balance_orig = 0;
	double interest_rate = 0;
	double nominal_interest_rate = 0;
	double escrow = 250;

	double monthly_payment = 0;
	double payment = 0;
	double interest = 0;
	double principal = 0;
	//double extra_payment;
	double tmp1, tmp2;
	uint32_t months = 0;
	//uint32_t years = 0;
	//uint32_t num1 = 0;

	if(argc != 4){
		Usage();
		exit(1);
	}
	loan_balance = atof(argv[1]);
	interest_rate = atof(argv[2]);
	loan_balance_orig = loan_balance;
	nominal_interest_rate = interest_rate/12/100;
	monthly_payment = atof(argv[3]);

	while((loan_balance-monthly_payment) > 0){

		tmp1 = nominal_interest_rate*loan_balance;
		
		tmp2 = (monthly_payment - tmp1);
		principal += tmp2;
		interest += tmp1;
		payment += monthly_payment;
		loan_balance -= tmp2;
		months++;
	}

	if(loan_balance > 0){
	//calculate final payment
	tmp1 = nominal_interest_rate*loan_balance;

	tmp2 = loan_balance_orig - principal;

	principal += tmp2;

	//payment += (monthly_payment - tmp1) + tmp1;

	payment += (tmp1+tmp2);
	interest += tmp1;
	loan_balance -= tmp2;
	months++;
	}else
		printf("error\n");

	printf("months: %u\n", months);
	printf("loan_balance: %.03lf\n", loan_balance);
	printf("payment: %.03lf\n", payment);
	printf("interest: %.03lf\n", interest);
	printf("principal: %.03lf\n", principal);

	return 0;
}
