Complete R script as of 140214