full implementation with all the test cases passing.