Refactor based on tianon's suggestions