Add test cases and fix bugs