Cleanup and refactor, add some missing documentation.