Some refactoring, better error messages.