Spec coverage and refactorings.

An initial effort to add a unit test suite for this library and extract any
common code where convenient.