Improved templateId algorithm and cleaned up