Error checking and cleanup