giant R file for 500, this has been split into functions for the package