refactored swapping code.