Fix bugs and improve test coverage