The code has been added to the R script and comments added.