def extract_with_context(lst, pred, before_context, after_context):
    """Extract URL and context from a given chunk.

    """
    rval = []
    start = 0
    length = 0
    while start < len(lst):
        usedfirst = False
        usedlast = False
        while start + length < len(lst
            ) and length < before_context + 1 and not pred(lst[start + length]
            ):
            length += 1
        while start + length < len(lst) and not pred(lst[start + length]):
            start += 1
        if start + length == len(lst):
            break
        while start + length < len(lst) and pred(lst[start + length]):
            extendlength = 1
            while (extendlength < after_context + 1 and start + length +
                extendlength < len(lst) and not pred(lst[start + length +
                extendlength])):
                extendlength += 1
            length += extendlength
            if start + length < len(lst) and not pred(lst[start + length]):
                extendlength = 1
                while (extendlength < before_context and start + length +
                    extendlength < len(lst) and not pred(lst[start + length +
                    extendlength])):
                    extendlength += 1
                if start + length + extendlength < len(lst) and pred(lst[
                    start + length + extendlength]):
                    length += extendlength
        if length > 0 and start + length <= len(lst):
            if start == 0:
                usedfirst = True
            if start + length == len(lst):
                usedlast = True
            rval.append((lst[start:start + length], usedfirst, usedlast))
        start += length
        length = 0
    return rval
