Fixes for flaws demonstrated by more complex templates.

Most of the fixes were to do with handling commateds in templates.
This is still slightly brittle.