also replace terms in safe function; consolidated replace_terms