Added unit tests, fixed bugs found by running tests, minor renaming and cleanup.