Refactor to more functional style