improved error handling and formatted code