Some code refactoring to provide more useful error messages.