Tidied up and commented code.