updated with more robust error-handling