Tidied up code and fixed small bugs