Refactored, and added some test cases.