solution to problem 5 and some refactoring