added final version of template-removal code