refactor based on @odoh code