Rewrote script as an R function