Tidied up the code to make it slightly easier to read.