import re


def fix_license(value, conversions):
    """
    Fix license string to match up current SPDX format.

    Args:
        value: the current license string
        conversions: list of known license format replacements

    Returns:
        string with the new license
    """
    # license ; should be replaced by ands so find it
    re_license_semicolon = re.compile(r'\s*;\s*')
    value = value.rstrip(';')
    value = re_license_semicolon.sub(' and ', value)
    # split using 'or', 'and' and parenthesis, ignore empty strings
    licenses = []
    for a in re.split(r'(\(|\)| and | AND | OR | or (?!later)|;)', value):
        if a != '':
            licenses.append(a)
    if not licenses:
        licenses.append(value)

    for (index, my_license) in enumerate(licenses):
        my_license = ' '.join(my_license.split())
        my_license = my_license.replace('ORlater', 'or later')
        my_license = my_license.replace('ORsim', 'or similar')
        if my_license in conversions:
            my_license = conversions[my_license]
        licenses[index] = my_license

    # create back new string with replaced licenses
    s = (
        ' '.join(licenses)
        .replace('( ', '(')
        .replace(' )', ')')
        .replace(' and ', ' AND ')
        .replace(' or ', ' OR ')
        .replace(' with ', ' WITH ')
    )
    return s