Tidied up code and added some user-configurable options.