Cleanup code + writing comments to functions

Cleanup code + writing comments to functions.
Other minor changes.