label load_failed:
    $ persistent.load_fails += 1
    if persistent.load_fails < 2:
        $ retry_load(persistent.last_load)
    else:
        scene black with fade
        "Your save failed to load! Do you want to try and recover it? If you select yes, then the mod will try to disaster recover your save. If it works, click once or twice to advance the renders and create a new save. If it throws another error or returns to this prompt the save is unrecoverable."
        menu:
            "Yes":
                $ retry_load(persistent.last_load)
            "Return to the Main Menu":
                $ _return = False
                return

init python:
    def reset_load_fail():
        persistent.load_fails = 0

    persistent.load_fails = 0
    config.load_failed_label = "load_failed"
    config.after_load_callbacks = [reset_load_fail]

    from renpy.compat.pickle import loads
    
    def remap(log, namemap):
        bool_map = map(check_log, log.log)
        true_indices = [i for i, x in enumerate(bool_map) if x]

        #TODO: Handle case when there is only one true_index?
        for ix, t_ix in enumerate(true_indices[:-1]):
            rb = log.log[t_ix]

            label = get_label(rb)
            next_label = get_label(log.log[true_indices[ix+1]])
            if label in namemap and next_label in namemap:
                rb.context.current = namemap[label]

            log.log[t_ix] = rb

    def check_log(rb):
        if not hasattr(rb, 'stores'):
            return False
        if not 'store' in rb.stores:
            return False
        if not '_last_say_who' in rb.stores['store']:
            return False

        return True

    def get_label(rb):
        return (rb.context.current[0].split('/')[-1], rb.stores['store']['_last_say_who'], rb.stores['store']['_last_say_what'])

    def retry_load(slot):
        # system load location
        location = renpy.savelocation.FileLocation(config.savedir)
        location.scan()

        # if not system , try local save location
        if slot not in location.list():
            location = renpy.savelocation.FileLocation(config.gamedir +'/saves')
            location.scan()

        log_data, signature = location.load(slot)
        roots, log = loads(log_data)

        new_namemap = {}
        for k,v in renpy.game.script.namemap.items():
            if isinstance(v, renpy.ast.Say):
                new_namemap[(v.name[0].split('/')[-1], v.who, v.what)] = v.name

        remap(log, new_namemap)
        log.unfreeze(roots, label="_after_load")

    def load(filename):
        """
        :doc: loadsave

        Loads the game state from the save slot `filename`. If the file is loaded
        successfully, this function never returns.
        """
        persistent.last_load = filename

        log_data, signature = renpy.loadsave.location.load(filename)

        if not renpy.savetoken.check_load(log_data, signature):
            return

        roots, log = loads(log_data)
        log.unfreeze(roots, label="_after_load")

    renpy.load = load