Added a bunch of comments and did a bit of refactoring