Tidied up the code and made it into a package