Major overhaul of the codebase

Mainly reformatting, but also straightening some code out and adding comments to dubious sections.