Cleaned up code and added a couple tests.