removed loops, changed to state machine (to allow breaks)
removed trailing spaces