Perform a calculation on the ``num`` most recent values. Requires a list.
    Valid values for ``oper`` are:

    - add: Add last ``num`` values together
    - mul: Multiple last ``num`` values together
    - mean: Calculate mean of last ``num`` values
    - median: Calculate median of last ``num`` values
    - median_low: Calculate low median of last ``num`` values
    - median_high: Calculate high median of last ``num`` values
    - median_grouped: Calculate grouped median of last ``num`` values
    - mode: Calculate mode of last ``num`` values

    USAGE:

    .. code-block:: yaml

        foo:
          calc.calc:
            - name: myregentry
            - num: 5
            - oper: mean

def calc(name, num, oper, minimum=0, maximum=0, ref=None):
    '''
    Perform a calculation on the ``num`` most recent values. Requires a list.
    Valid values for ``oper`` are:

    - add: Add last ``num`` values together
    - mul: Multiple last ``num`` values together
    - mean: Calculate mean of last ``num`` values
    - median: Calculate median of last ``num`` values
    - median_low: Calculate low median of last ``num`` values
    - median_high: Calculate high median of last ``num`` values
    - median_grouped: Calculate grouped median of last ``num`` values
    - mode: Calculate mode of last ``num`` values

    USAGE:

    .. code-block:: yaml

        foo:
          calc.calc:
            - name: myregentry
            - num: 5
            - oper: mean
    '''
    ret = {'name': name,
           'changes': {},
           'comment': '',
           'result': True}
    if name not in __reg__:
        ret['comment'] = '{0} not found in register'.format(name)
        ret['result'] = False

    def opadd(vals):
        sum = 0
        for val in vals:
            sum = sum + val
        return sum

    def opmul(vals):
        prod = 0
        for val in vals:
            prod = prod * val
        return prod

    ops = {
        'add': opadd,
        'mul': opmul,
        'mean': statistics.mean,
        'median': statistics.median,
        'median_low': statistics.median_low,
        'median_high': statistics.median_high,
        'median_grouped': statistics.median_grouped,
        'mode': statistics.mode,
    }

    count = 0
    vals = []
    __reg__[name]['val'].reverse()
    for regitem in __reg__[name]['val']:
        count += 1
        if count > num:
            break
        if ref is None:
            vals.append(regitem)
        else:
            vals.append(regitem[ref])

    answer = ops[oper](vals)

    if minimum > 0 and answer < minimum:
        ret['result'] = False

    if 0 < maximum < answer:
        ret['result'] = False

    ret['changes'] = {
        'Number of values': len(vals),
        'Operator': oper,
        'Answer': answer,
    }
    return ret