Refactored code somewhat. Made error messages more sensible.