Refactored for clarity; improved test coverage.