Refactored code to allow it to be re-usable in other apps.