refactored a bit to use a more map/reduce like flow