import linecache


def checkline(filename, lineno, ui):
    """Return line number of first line at or after input
    argument such that if the input points to a 'def', the
    returned line number is the first
    non-blank/non-comment line to follow.  If the input
    points to a blank or comment line, return 0.  At end
    of file, also return 0."""

    line = linecache.getline(filename, lineno)
    if not line:
        ui.print('*** End of file')
        return 0
    line = line.strip()
    # Don't allow setting breakpoint at a blank line
    if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"):
        ui.print('*** Blank or comment')
        return 0
    # When a file is read in and a breakpoint is at
    # the 'def' statement, the system stops there at
    # code parse time.  We don't want that, so all breakpoints
    # set at 'def' statements are moved one line onward
    if line[:3] == 'def':
        instr = ''
        brackets = 0
        while 1:
            skipone = 0
            for c in line:
                if instr:
                    if skipone:
                        skipone = 0
                    elif c == '\\':
                        skipone = 1
                    elif c == instr:
                        instr = ''
                elif c == '#':
                    break
                elif c in ('"', "'"):
                    instr = c
                elif c in ('(', '{', '['):
                    brackets = brackets + 1
                elif c in (')', '}', ']'):
                    brackets = brackets - 1
            lineno = lineno + 1
            line = linecache.getline(filename, lineno)
            if not line:
                ui.print('*** end of file')
                return 0
            line = line.strip()
            if not line:
                continue   # Blank line
            if brackets <= 0 and line[0] not in ('#', '"', "'"):
                break
    return lineno