import re
import math


def parse_jobs_from_MAKE(MAKE, unlimited=999999):
    """
    Parse an environment variable like :envvar:`MAKE` for the number of
    jobs specified. This looks at arguments ``-j``, ``--jobs``, ``-l``,
    ``--load-average``.

    INPUT:

    - ``MAKE`` -- The value of :envvar:`MAKE` or :envvar:`MAKEFLAGS`.

    - ``unlimited`` -- The value to return when ``MAKE`` contains ``-j``
      without argument and no ``-l`` option.  Normally this is interpreted
      as "unlimited".

    OUTPUT:

    The number of jobs specified by that variable.  Raise ``KeyError``
    if no number of jobs is specified in ``MAKE``.
    """
    # First, find value of -j
    # Since this is doing a greedy match on the left and non-greedy on the right,
    # we find the last -j or --jobs
    (j, num) = re.subn(r'^(.* )?(-j *|--jobs(=(?=[0-9])| +))([0-9]*)( .*?)?$', r'\4', MAKE, count=1)
    if num < 1:
        # No replacement done, i.e. no -j option found
        raise KeyError("No number of jobs specified")
    elif j == "":
        # j is empty: unlimited number of jobs! :-)
        j = unlimited
    else:
        j = int(j)
        if j <= 0:
            raise ValueError("Non-positive value specified for -j")

    # Next, find the value of -l
    # If it is specified, use this as an upper bound on j
    (l, num) = re.subn(r'^(.* )?(-l *|--(load-average|max-load)(=(?=[0-9])| +))([0-9.]*)( .*?)?$', r'\5', MAKE, count=1)
    if num < 1:
        # No replacement done, i.e. no -l option found
        pass
    elif not l:
        # No load limit specified
        pass
    else:
        l = int(math.ceil(float(l)))
        # A load limit will never prevent starting at least one job
        if l <= 1:
            l = 1
        j = min(j, l)

    return j