Refactoring and documentation

Doc blocks for everything and a few minor improvements via code refactoring.