Refactor labeling code