Updated TemplateGenerator to perform better

Clean version of this pull request.