Fixed remove-and-replace code to work in two passes