Refactored templates, moved some logic out of common library