Refactored to make problem 3 more readable