#!/usr/bin/perl
push(@INC,"/www/cgi-bin");

# First tell browser that this is an HTML document being printed

print "Content-type:text/html\n\n";

# The following formats the incoming arguments and puts them into the
# vector $FORM.  Access %FORM with variables $FORM{name}.  Names in
# interest.pl are loan, interest, time, payment

read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    $value =~ s/\n/ /g; # replace newlines with spaces
    $FORM{$name} = $value;
}

# Set up the web variables locally
$p = $FORM{loan};
$i = $FORM{interest};
$n = $FORM{time};
$m = $FORM{payment};

# Start the HTML printing
print "<html>\n";
print "<head>\n";
print "<title>Results of Interest Calculation</title>\n";
print "</head>\n";
print "<body>\n<center>\n";

print "<p>\n";
print "Loan Amount: \$$p<br>\n";
print "Interest Rate: $i%<br>\n";
print "<p>\n";

# Now change interest rate to be used
$i = $i / 100;

# If the monthly interest is greater than the monthly payment, stop
if((1 + $i / 12) * $p - $m < $p) {
    print "You won't be able to pay off the loan!";
    print "Your payments aren't high enough!";
}

if($n == 0) {
    while($p >= 0) {
        $p = (1 + $i / 12) * $p - $m;
        $n++
    }
    print "Monthly Payment: $m\n<br>";
    print "<b>Number of Payments: $n\n</b>";
}

if($m == 0) {
    if($i == 0) {
        print "Number of Payments: 1<br>\n";
        print "<b>Monthly Payment: $p\n";
    }
    else {
        $m = ($p * $i) / (12 * (1 - (1 + $i / 12) ** (-$n)));
        $m = int($m*100) / 100;
        print "Number of Payments: $n<br>\n";
        print "<b>Monthly Payment: $m</b>\n";
    }
}

print "</center>\n</body>\n</html>";
