Tidied up the code a lot.