Refactored and tidied up.