fix bugs and add test cases