Write to temp file to avoid corrupted files