Added internal while loop, cleaned up code
Corrected bug with changes in previous commit