Added template functionality and cleaned up some mess