Refactor to flat_map