'We fetch all new mail headers and search for the right
X-OfflineImap line by hand. The response from the server has form:
\'OK\',
\'185 (RFC822.HEADER {1789}\',
\'... mail headers ...\'
\' UID 2444)\',
\'186 (RFC822.HEADER {1789}\',
\'... 2nd mail headers ...\'
\' UID 2445)\'
We need to locate the UID just after mail headers containing our
X-OfflineIMAP line.
Returns UID when found, 0 when not found.'

def __savemessage_fetchheaders(self, imapobj, headername, headervalue):

    self.ui.debug('imap', ('__savemessage_fetchheaders    called    for    %s:    %s' % (headername, headervalue)))
    if self.getmessagelist():
        start = (1 + max(self.getmessagelist().keys()))
    else:
        start = 1
    result = imapobj.uid('FETCH', bytearray(('%d:*' % start)), 'rfc822.header')
    if (result[0] != 'OK'):
        raise OfflineImapError(('Error    fetching    mail    headers:    %s' % '.    '.join(result[1])), OfflineImapError.ERROR.MESSAGE)
    result = result[1]
    found = None
    for item in result:
        if ((found is None) and (type(item) == tuple)):
            if re.search(('(?:^|\\r|\\n)%s:\\s*%s(?:\\r|\\n)' % (headername, headervalue)), item[1], flags=re.IGNORECASE):
                found = item[0]
        elif (found is not None):
            if (type(item) == type('')):
                uid = re.search('UID\\s+(\\d+)', item, flags=re.IGNORECASE)
                if uid:
                    return int(uid.group(1))
                else:
                    uid = re.search('\\d+\\s+\\(UID\\s+(\\d+)', found, flags=re.IGNORECASE)
                    if uid:
                        return int(uid.group(1))
                    self.ui.warn(("Can't    parse    FETCH    response,    can't    find    UID    in    %s" % item))
                    self.ui.debug('imap', ('Got:    %s' % repr(result)))
            else:
                self.ui.warn(("Can't    parse    FETCH    response,    we    awaited    string:    %s" % repr(item)))
    return 0
