Fix busy-loop on upload error (and avoid a few other race conditions).

Current version hangs on upload when the Mega server reports an error -- what's worse is that it hangs in a busy loop using 100% CPU!

While fixing the issue (which is due to a `break` inside a `select` inside a `for` which breaks out of the `select` but not out of the enclosing `for`) I came across a few other oddities, some of which represent potential race conditions themselves, which I tried to fix as well.