fix and refactor for #2721