Refactored to using more functional reduce instead of each