refactoring substitution code