refactor and complete map-reduce