Refactored implementation based on Henris comments