Fixing some bugs, and adding test cases.