Fixed last bugs, and added test cases