# Try commenting out the warnings/errors in the following function, and 
# the tryCatch handlers below
broken_function <- function(){
  print("started")
  warning("This is warning")
  print("done warning")
  stop("This is an error")
  print("Done with the error")
}

f <- function(){
  message("This is a message")
  warning("This is a warning")
  #stop("This is an error")
  return(10)
}

result <- tryCatch({
          # Code goes here
          f()
         },
         #message = function(m){
         #   print("Got a message")
         #  print(m)
         #   return(-1)
         #},
         #warning = function(w){
         #  print("Got a warning")
         # print(w)
         #   return(-2)
         #}, 
         error = function(e){
           print("Got an error")
           print(e)
         },
         finally = {
           print("Finally...")
         })

# Pattern for repeatedly trying something until success
success <- FALSE
while (!success){
  success <- tryCatch({
      !(runif(1,0,1) < 0.99)
    },error = function(e){
      return(FALSE)
    })
}


## Bootstrap/Email Example

# samples: numeric value, number of bootstrap samples
# data: the data to be resampled, should be atomic vector
# statistic: a function to be run on the resampled data
# ...: additional arguments for the statistic function
bootstrap <- function(samples, 
                      data, 
                      statistic, 
                      ...){
  t(sapply(1:samples, function(i){
    statistic(sample(data, replace = TRUE), ...)
  }))
}


X <- rnorm(1000)
bootstrap(100, X, mean)

bootstrap(100, X, function(z){c(mean(z), median(z))})
data(iris)
coeffs <- bootstrap(100, 1:nrow(iris), function(idx){
  dat <- iris[idx,]
  lm(Sepal.Length ~ ., data = dat)$coefficients
})



## Example with email ##
install.packages("sendmailR")
library(sendmailR)
errorEmail <- function(msg){
  mailControl  <- list(smtpServer="ns-mx.uiowa.edu")
  sendmail(from="grant-brown@uiowa.edu", 
           to="grant-brown@uiowa.edu", 
           subject="Errors encountered in bootstrap script.", 
           msg=msg, 
           control=mailControl)
}

tryCatch({
  X <- rnorm(1000)
  boot.samples <- bootstrap(100, X, function(z){
     if (runif(1,0,1) < 0.01){stop("Errorz")}
     mean(z)
  })
  },
  error = function(e){
    errorEmail(e)
})

