Refactored the flipping algorithm