Refactored to speed up.