How to get out of this loop?