This logic seems to be duplicated in a few places. We should refactor it out.