Refactored code. Untested.