init -1 python:
    def ending_image():
        #0b0000, DCBA, flash the bits with |=, check with &
        endings = 0b0000
        _e = 0b1
        for i in range(1, 5):
            fn = "e"+str(i)+"of4"
            endings |= (_e * renpy.seen_image(fn))
            _e = _e << 0b1
        persistent.old_endings = persistent.endings
        persistent.endings = endings


init python:

    def next_story_chapter():
        global chapter_list_index, current_chapter, ending_route_number

        # Add check "is_end_reached" to have this if statement be executed only once when finishing the general chapters
        if not is_end_reached and is_end_of_chapters():
            process_ending()
            
        if chapter_list_index < chapter_list_length:
            chapter_list_index += 1
            current_chapter = chapter_list[chapter_list_index]
            renpy.call(current_chapter)
        else:
            end_story()
    

    def is_end_of_chapters():
        return chapter_list_index >= chapter_list_length


    def process_ending():
        global ending_route_number

        ending_route_number = get_ending()
        add_ending_chapters()
        update_ending_variables()


    def add_ending_chapters():
        global chapter_list

        if ending_route_number in ending_routes:
            chapter_list.extend(ending_routes[ending_route_number])


    def update_ending_variables():
        global chapter_list_length
        global is_end_reached

        # chapter_list_length is updated to reflect the addition to the chapter_list array
        chapter_list_length = get_chapter_list_length()
        is_end_reached = True

    
    def get_chapter_list_length():
        return len(chapter_list) - 1


    
    def end_story():
        ending_image()
        renpy.call("lending")