Improved fix for recursive substitutions.

See commit 69e5411f80560bba03fdb0ae8922ec048ba114a5.