Refactor to create a general version for scan_and_replace