Add testing for all functions.

This change takes this library up to 100% test coverage. In doing so a
few bugs were cleaned up, a lot of the code was simplified, and
basically the whole things should be more robust now.