This function should ideally be able to replace variables recursively, modifying the current code to do this looks tough, can we refactor this for a cleaner approach ?