improved error handling and refactored some common code in