fixed an endless loop - still needs some cleanup, but should be stable