Added error handling and checks