This whole thing looks like it could be reduced to a `map` and a `reduce` call.