refactored this to be a bit tidier and more efficient