Use more templates; Move some functions

so that they can be included and used by other files when needed