Return the metadata, a boolean to indicate if a jupyter section was found,
     the first cell of notebook if some metadata is found outside of the jupyter section, and next loc in text

def header_to_metadata_and_cell(lines, header_prefix, ext=None):
    """
    Return the metadata, a boolean to indicate if a jupyter section was found,
     the first cell of notebook if some metadata is found outside of the jupyter section, and next loc in text
    """

    header = []
    jupyter = []
    injupyter = False
    ended = False
    metadata = {}
    start = 0
    i = -1

    comment = '#' if header_prefix == "#'" else header_prefix

    encoding_re = re.compile(r'^[ \t\f]*{}.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)'.format(comment))

    for i, line in enumerate(lines):
        if i == 0 and line.startswith(comment + '!'):
            metadata.setdefault('jupytext', {})['executable'] = line[2:]
            start = i + 1
            continue
        if i == 0 or (i == 1 and not encoding_re.match(lines[0])):
            encoding = encoding_re.match(line)
            if encoding:
                if encoding.group(1) != 'utf-8':
                    raise ValueError('Encodings other than utf-8 are not supported')
                metadata.setdefault('jupytext', {})['encoding'] = line
                start = i + 1
                continue

        if not line.startswith(header_prefix):
            break

        line = uncomment_line(line, header_prefix)

        if i == start:
            if _HEADER_RE.match(line):
                continue
            else:
                break

        if i > start and _HEADER_RE.match(line):
            ended = True
            break

        if _JUPYTER_RE.match(line):
            injupyter = True
        elif not _LEFTSPACE_RE.match(line):
            injupyter = False

        if injupyter:
            jupyter.append(line)
        else:
            header.append(line)

    if ended:
        if jupyter:
            metadata.update(yaml.safe_load('\n'.join(jupyter))['jupyter'])

        lines_to_next_cell = 1
        if len(lines) > i + 1:
            line = uncomment_line(lines[i + 1], header_prefix)
            if not _BLANK_RE.match(line):
                lines_to_next_cell = 0
            else:
                i = i + 1
        else:
            lines_to_next_cell = 0

        if header:
            cell = new_raw_cell(source='\n'.join(['---'] + header + ['---']),
                                metadata={} if lines_to_next_cell == pep8_lines_between_cells(
                                    ['---'], lines[i + 1:], ext) else {'lines_to_next_cell': lines_to_next_cell})
        else:
            cell = None

        return metadata, jupyter, cell, i + 1

    return metadata, False, None, start