stable refactored version