Changed to a do-while loop
Some optimisations