replaced clumsy temp variable with do-while loop