implemented swapping logic