Add documentation and minor refactoring