Functional refactor thanks to @gubatron.