def mangleIR(data, ignore_errors=False):
    """Mangle a raw Kira data packet into shorthand"""
    try:
        # Packet mangling algorithm inspired by Rex Becket's kirarx vera plugin
        # Determine a median value for the timing packets and categorize each
        # timing as longer or shorter than that. This will always work for signals
        # that use pulse width modulation (since varying by long-short is basically
        # the definition of what PWM is). By lucky coincidence this also works with
        # the RC-5/RC-6 encodings used by Phillips (manchester encoding)
        # because time variations of opposite-phase/same-phase are either N or 2*N
        if isinstance(data, bytes):
            data = data.decode('ascii')
        data = data.strip()
        times = [int(x, 16) for x in data.split()[2:]]
        minTime = min(times[2:-1])
        maxTime = max(times[2:-1])
        margin = (maxTime - minTime) / 2 + minTime
        return ''.join([(x < margin and 'S' or 'L') for x in times])
    except:
        # Probably a mangled packet.
        if not ignore_errors:
            raise
Mangle a raw Kira data packet into shorthand