Better error handling and code simplified