Template refactoring + fixes and improvements