Better error messages and minor refactoring.