Fixed bugs. Added better test cases.