Fix 3-way case and refactor the code