tidied up structure, added more comments

Reshuffled some of the structure and added a bunch more comments to
better explain what everything is.