Fix some bugs and improve test suite