Added a load of javadoc and comments to make it clearer what is happening where