added some error handling and failsafe