cleanup & finish debugging

 * seperate middleware with template
 * proper switch in Environment
 * cleaned some unit tests
 * fixed template origin not always created