slightly more robust error handling, refactored code