Fix bugs, add tests.