Reduce duplication. Also improve error message
Fix
Merge pull request #1044 from alex/reduce-duplication

Reduce duplication. Also improve error message