Refactored to use state functions.