refactored imperative implementation