refactoring

Pretty big refactor/rewrite of a lot of the logic in the template. This should take care of the race conditions.