Add test suite and fix some corner cases