Tidied up the code and split it into more files