while loop causing infinite loop