Rewrote main templating function