Better implementation of problem 6 along with some refactoring.