Some extra error handling and cleanup