Added documentation in comments to code

Also some refactoring.