Added extra error handling and debugging