Refactoring imap (in progress)