Refactored code to separate some the backend stuff from the UI.