Completed code, passes all test cases and works great