/*************************************************
FINANCIAL SIMULATION

You have a bank account whose annual interest
rate depends on the amount of money you have
in your account at the beginning of each year.
Your annual rate starts at 3%, and grows by an
additional half a percent for each thousand
dollars in your account up to, but not exceeding
8%. Interest in this account is compounded monthly
at the annual rate.  Each year you also make a
transaction (before the bank figures out what
your rate is).  Write a program that simulates
these financial interactions for 5 years.  At
the beginning of each year it should ask the
user whether he wants to make a deposit or
withdrawl and for how much.  At the end, it
should print out the balance at the end of the
5th year.
*************************************************/
#include <stdio.h>

double transaction(double bal);
double intrate(double bal);
double compound(double rate);

int main() {
  double bal = 0.0;

  // Simulate 5 years
  for(int i = 0; i < 5; i++) {
    bal = transaction(bal);
    double rate = intrate(bal);
    bal = bal*compound(rate);
  }

  // Print out final balance
  printf("Balance = $%.2f\n", bal);

  return 0;
}

/*******************************************
 ** Interacts with user to perform transaction
 ** and returns new balance.
 *******************************************/
double transaction(double bal) {
  // Get type of transaction
  printf("Enter w:withdrawl or d:deposit ");
  fflush(stdout);
  char act;
  scanf(" %c", &act);

  // Get amount of transaction
  printf("Enter amount: ");
  fflush(stdout);
  double amount;
  scanf(" %lg", &amount);

  // Get new Balance figure
  if (act == 'w') {
    bal = bal - amount;
  }
  else {
    bal = bal + amount;
  }

  return bal;
}

/*******************************************
 ** Computes interest rate based on Balance.
 *******************************************/
double intrate(double bal) {
  // Get # of thousands
  int thous = bal/1000;

  // Calc rate
  double rate = 3 + thous*0.5;
  if (rate > 8) {
    rate = 8;
  }

  return rate;
}

/*******************************************
 ** Gives the value of one dollar after a
 ** year of monthly compounded interest at
 ** annual rate rate.
 *******************************************/
double compound(double rate) {
  // Simulate year with monthly compounding
  double scalerate = rate/100;
  double total = 1.0;
  for(int i = 0; i < 12; i++) {
    total = total*(1 + scalerate/12);
  }

  return total;
}