refactored and tested Problem 5