Fix bugs and write tests.