Implemented new template system.

Please note it is not fully tested.
If there is any problems, I'll look at them tomorrow.