Moved duplicate check to outside of the while loop