Convert nested if structure to while loop