Refactored and added failure handling