Refactored for readability; expanded test coverage.