refactored swap function