better error handling and cleanup