Document code, improve readability, refactor

All functions and structures are documented. I have also improved
readability in places and refactored some poor naming choices.