Fix bugs, add test cases