Partial refactoring for problem 4.