now with tests, and fixed bugs exposed by them