Some refactoring to make the code clearer.