Refactored to make it easier to test on devices.