Refactored core logic to be clearer.