Print substitution code into the library.

Add some additional checking which wasn't present before.

Unit test the results.