Completely rewrote the templating

Templating was a bit of a mess, this is an attempt to make things much
easier to follow.

Signed-off-by: Gergely Nagy <algernon@madhouse-project.org>