Minor refactoring and giving more detailed error messages.