fixed bug: moved several statements outside while loop
delete unused import