Substantial refactoring.  Added more tests.