more complete error handling and refactoring for clarity