Fixed a slew of bugs related to templates and variables...

Talked to Ryan and it seems like this work is not going to be continued but I'll submit the PR anyway.