Refactoring and template improvements