Updated R code following updates from Pete Henrys