reworked substitution logic and add tests

Change-Id: I908dc601067b9e4491dd8e3163125fee0ff85508