refactor for less duplication, more robustness