Fixed bugs, added test cases