Improve replacement function