implement most of the substitution logic

paired with @glennfellman