Added a separate function to handle reference replacement