import json
from shutil import copyfile


def LoadJSONFile(path,appendStr,count=0):
    """ Loads data from a JSON file and corrects unfinished runs by appending a
    string to the file.

    Args:
        path:           path to json file
        appendStr:      string to append in case of a JSONDecodeError
        count:          number of times this function was called recursively

    Returns:
        dict object representing the loaded data

    Raises:
        Exception: Unable to correctly load the file with the appended string.

    Note:
        For portability, this function detects a ValueError instead of a
        JSONDecodeError which inherits from it.

    """
    filemod = path[:-5]+"-mod"+".json"
    try:
        if count == 0:
            data = json.load(open(path))
        elif count == 1:
            data = json.load(open(filemod))
        else:
            raise Exception('LoadJSONFile was not able to correct the file "{}" with an appended "{}". '
                'Check the file manually.'.format(path,appendStr))
        return data
    except ValueError:
        copyfile(path,filemod)
        fh = open(filemod, "a")
        fh.write(appendStr)
        fh.close()
        return LoadJSONFile(path,appendStr,count+1)