Refactor template handling (fixes #106 and #67)