Reorganised code and added more comments. Missing from previous commit.