Reduced code with all test cases working