Code health improvements

This PR increases the health of our code by adding lots of
tests and comments. In cases, code was refactored to use
existing functions rather than duplicating code.

See each commit message for details.

Includes PR #171