Detect the end condition correctly.