Tidied up the code a bit and fixed a few typos