Some refactoring to make the code more idiomatic.