Formatting and bug fixes

Formatted the code to fit more with coding conventions, added a bit more
documentation, and fixed some minor bugs I discovered.