Tidied up code and added some documentation