fixed an issue with break

I was not breaking out of the correct loop.

Also added some better error handling.