#!/bin/bash
# program myamort
# version 1.0  
# written by Andrew V. Newman
# last modified Wed Feb 25 17:37:04 MST 2004

# program to calculate monthly payment on a loan

# This is a default response if you do not give any input variables
if [ ${#} -lt "2" ]; then
   echo "Usage: amort 'LOAN' 'APR' [TRM] [CMP] [PPY]"
   echo "   where LOAN is amount in dollars"
   echo "       APR is in fractions of 100 (i.e. 6.5% is 6.5)"
   echo "     (following are optional:)"
   echo "       TRM is term in years [30 is default]"
   echo "       CMP is compounds per year [12 is default--monthly]"
   echo "       PPY is payments per year [12 is default]"
   echo "   Example:"
   echo "     amort 150000 6.5 30 12 12"
   exit 1
fi

# These need to be input every time
  LOAN=312000  # Amount of loan
  APR=0.06     # Annual Percentange Rate
  LOAN=$1      # Amount of loan
  APR=`echo $2 | awk '{print $1/100}' ` # Annual Percentange Rate

# These may or may not be input
  TRM=30  # Term of loan in years
    if [ $3 ]; then  TRM=$3 ; fi
  CMP=12  # Number of comounds/year
    if [ $4 ]; then  CMP=$4 ; fi
  PPY=12  # Number of payments/year
    if [ $5 ]; then  PPY=$5 ; fi

# Calculate Monthly Payment
  MPMT=` echo $APR | awk '{
	R=(1+$1/CMP)^(CMP/PPY)}
	END {printf "%8.2f", LOAN*(R^(TRM*PPY)*(R-1))/(R^(TRM*PPY)-1)
	}' LOAN=$LOAN NPMTS=$NPMTS CMP=$CMP PPY=$PPY TRM=$TRM `
LOANK=`echo $LOAN | awk '{print "\$" $1/1000 "K"}'`
APR100=`echo $APR | awk '{print $1*100}'`
printf "For:\n LOAN: $LOANK\n APR $APR100 over $TRM years\n $PPY pmnt/yr at: \$%7.2f\n" $MPMT

# exit cleanly
exit 0
