refactored median functions