Tidied up code to make use of functions, also allowed for user specified directories to save output.