Fixed deleting templates before checking if reference still exists.