Move waiting logic for imap stop to the backend.

Also, improve quit and cleanup calls.