Refactor to map-reduce