Refine the logic to make it more understandable