implement most of the substitution logic
paired with @glennfellman
Merge pull request #1 from moritzg91/master

implement most of the substitution logic