Significant updates to R script; function can now be optimized