Tidying up the code, adding comments.