import warnings


def _split_sections(lines):
    """
    Split rigaku file into sections

    Returns a list of sections [(name, body, index)] where name is the section
    type, body is the list of lines between *RAS_name_START and *RAS_name_END
    and index is the 1-origin index of *RAS_name_START (or the 0-origin index
    of the first line of the body).
    """
    if lines[0] != b"*RAS_DATA_START":
        raise ValueError("not a Rigaku XRD RAS file")

    last_index = len(lines) - 1
    while last_index > 0 and lines[last_index] != b"*RAS_DATA_END":
        if lines[last_index] != b"":
           warnings.warn("Non-empty line found after *RAS_DATA_END: '%s' at line %d"%(lines[last_index], last_index))
        last_index -= 1

    sections = []
    end_target = None
    start_index = 1000000000 # initialize with int to keep linter happy
    for index, line in enumerate(lines[1:last_index]):
        if line == end_target:
            # Note: index chosen so that the section includes
            # "*RAS_section_START" but not "*RAS_section_END"
            name = lines[start_index+1][5:-6]
            body = lines[start_index+2:index+1]
            sections.append((name, body, start_index+1))
            end_target = None
        elif end_target is None:
            if not (line.startswith(b"*RAS_") and line.endswith(b"_START")):
                raise ValueError("Rigaku expected section start at line %d"
                                 %(index+2))
            start_index = index
            end_target = line[:-6] + b"_END"
        #else: accumulate into current section
    if end_target is not None:
        raise ValueError("Rigaku file incomplete: final section is not closed")
    return sections