Optimize doctest generation. Closes #1226