Fixed refactoring issues and adding template support