import multiprocessing


def set_threads(threads: int, set_global: bool = True) -> int:
    """Parse and set the (global) number of threads.

    Parameters
    ----------
    threads : int
        The number of threads.
        If larger than available cores, it is trimmed to the available maximum.
        If 0, it is set to the maximum cores available.
        If negative, it indicates how many cores NOT to use.
    set_global : bool
        If False, the number of threads is only parsed to a valid value.
        If True, the number of threads is saved as a global variable.
        Default is True.

    Returns
    -------
    : int
        The number of threads.
    """
    max_cpu_count = multiprocessing.cpu_count()
    if threads > max_cpu_count:
        threads = max_cpu_count
    else:
        while threads <= 0:
            threads += max_cpu_count
    if set_global:
        global MAX_THREADS
        MAX_THREADS = threads
    return threads