Lots of cleanup, documenting, and refactoring.