def _convert_write_result(operation, command, result):
    """Convert a legacy write result to write commmand format."""
    affected = result.get('n', 0)
    res = {'ok': 1, 'n': affected}
    errmsg = result.get('errmsg', result.get('err', ''))
    if errmsg:
        if result.get('wtimeout'):
            res['writeConcernError'] = {'errmsg': errmsg, 'code': 64,
                'errInfo': {'wtimeout': True}}
        else:
            error = {'index': 0, 'code': result.get('code', 8), 'errmsg':
                errmsg}
            if 'errInfo' in result:
                error['errInfo'] = result['errInfo']
            res['writeErrors'] = [error]
            return res
    if operation == 'insert':
        res['n'] = len(command['documents'])
    elif operation == 'update':
        if 'upserted' in result:
            res['upserted'] = [{'index': 0, '_id': result['upserted']}]
        elif result.get('updatedExisting') is False and affected == 1:
            update = command['updates'][0]
            _id = update['u'].get('_id', update['q'].get('_id'))
            res['upserted'] = [{'index': 0, '_id': _id}]
    return res
