#!/usr/bin/perl
push(@INC,"/www/cgi-bin");
require "cgi-lib.pl";
&ReadParse;
print &PrintHeader;

#
# Set up the web variables locally
#

$p = $in{loan};
$i = $in{interest};
$n = $in{time};
$m = $in{payment};

#
# Now change interest rate to be used
# Let c = 1 + i/12, where i is the decimal form of the interest rate
#  (i.e. 10% = 0.10)
#

$c = 1 + ($i/100)/12;

#
# Find number of total payments, given amount of each payment
# (Top half of HTML page)
#

if($m == 0) {
    $m = (($c**$n) * $p * ($c - 1)) / ($c**$n - 1);
    $m = int($m * 100 + 1) / 100;
    $s1 = "Number of Payments: $n";
    $s2 = "<b>Monthly Payment: \$$m</b>";
}

#
# Find amount of each monthly payment, given number of payments
# (Bottom half of HTML page)
#

if($n == 0) {
    $n = log($m / ($p - $p*$c + $m)) / log($c);
    $s1 = "Monthly Payment: \$$m";
    $s2 = "<b>Number of Payments: $n</b>";
}

#
# Make the table to print out interest paid for each month
# The resulting html code is stored in string s3 to be printed out
# at the end of the script.
#

$d = 1;
while($p > 0) {
    $pi = $c * $p - $p;
    $pi = int($pi * 100 + 1) / 100;

    # Total Interest
    $ti += $pi;

    $p = $c * $p - $m;
    if($p < 0) {
        $p = 0;
    }
    $p = int($p * 100) / 100;

    $s3 .= "<tr>\n";
    $s3 .= "<td>$d</td><td>$pi</td><td>$p</td>\n";
    $s3 .= "</tr>\n";
    $d++;
}

#
# Print the HTML document
# s1 and s2 are strings from the calculations above.  s1 is the string
# containing either n or m, whichever the user did input.  s2 is the
# string with the result from the calculation, calculating whatever
# the user did not input and thus was looking for.  s3 is the string
# containing the table created above to show each payment and how much
# interest is contained in each payment.
#

print <<"endhtml";
<html>
<head>
<title>Results of Interest Calculation</title>
</head>
<body>
<center>
<p>
Loan Amount: \$$in{loan}<br>\n
Interest Rate: $i%<br>\n
</p>
<p>
$s1
<br>
$s2
</p>
<table border=1>
<tr>
<td>Month</td><td>Interest Paid Off</td><td>New Loan Amount</td>
</tr>
$s3
</table>
Total Interest Paid: <b>$ti</b>
</center>
</body>
</html>
endhtml
