More careful implementation of replace