loanIncreasingBasic <- function(P=12000, intrPercent=6, years=10, monthsWithOutPayments=18) { 
  # monthsWithOutPayments, used for student loans.  Interest acrues, compounded monthly.  
  # time for Amortization begins after that
  I <- intrPercent
  L <- years #for ease of notation
  J <- I/(12 * 100)
  P <- P * ((1+J) ^ monthsWithOutPayments)  # for student loans
  N <- 12 * L
  M <- P*J/(1-(1+J)^(-N))

  counter <- 0
  totPayments <- M
  monthlyPayments <- M


  Pt <- P # current principal or amount of the loan
  currP <- NULL  # vector tracking Principal after each payment 
  while(Pt>=0) {

    #Recalculate interest every 3 months
    int <- max(3, I + round((rnorm(1)),3))
    I <- min(21, int)
    counter <- (counter + 1)
    if ((counter %% 3) == 0)  {
      int <- max(3, I + abs(round((rnorm(1)),3)))
      I <- min(21, int)
    } else if ((counter %% 10) == 0) {
      int <- max(3, I + round(abs(rnorm(1)),3))
      I <- min(21, int)
    }

    # RECALCULATE
    J <- I/(12 * 100)
    N <- 12 * L
    M <- P*J/(1-(1+J)^(-N))
    totPayments <- totPayments + M
    monthlyPayments <- c(monthlyPayments, M)    
    #-------------------------

    H <- Pt * J # this is the current monthly interest
    C <- M - H # this is your monthly payment minus your monthly interest, so it is the amount of principal you pay for that month
    Pt <- Pt - C # this is the new balance of your principal of your loan
  } # The loop continues until the value Q (and hence P) goes to zero
 return(list(totPayments, monthlyPayments))
}


cat("\n")
maxTrials <- 10000


tmp <- NULL
totalRepayAmts<-NULL
mPayments<-NULL
allmPayments <- NULL

noOfCheckpoints <- 400
interv <- (maxTrials / noOfCheckpoints)
counter <- 1

while (counter <= noOfCheckpoints) {
  start <- interv * (counter-1)+1
  finish <- interv * counter
  counter <- counter + 1

  for (i in start:finish) {
     tmp <- loanIncreasingBasic()  
     #cat("tmp[[2]] is: ", tmp[[2]], "\n")
     totalRepayAmts[[i]] <- tmp[[1]]
     mPayments[[i]] <- tmp[[2]]
     allmPayments <- c(allmPayments, unlist(mPayments[[i]]))
  }

  #000. cat("-----------------------------------------\n")
  cat("NUMBER OF TRIALS SO FAR: ", finish, "\n")
  cat("Summary for Total Payments:", summary(totalRepayAmts),"\n")
  cat("Summary for All Monthly Payments:", summary(allmPayments), "\n")
  cat("\n")
} # end of While loop
