Change some for loop to map-reduce