Template fixes, code refactoring