ANGLES = {
    'N': (-23, 22),
    'NO': (292, 337),
    'O': (247, 292),
    'SO': (202, 247),
    'S': (157, 202),
    'SE': (112, 157),
    'E': (67, 112),
    'NE': (22, 67)
}

ORIENTATIONS = ANGLES.keys()


def merge_intervals(l, wrap=360):
    """Merge a list of intervals, assuming the space is cyclic.  The
    intervals should already by sorted by start value."""
    if l == []:
        return []
    result = list()
    # Transform the 2-tuple into a 2-list to be able to modify it
    result.append(list(l[0]))
    for (start, stop) in l:
        current = result[-1]
        if start > current[1]:
            result.append([start, stop])
        else:
            result[-1][1] = max(result[-1][1], stop)
    if len(result) == 1:
        return result
    # Handle the cyclicity by merging the ends if necessary
    last = result[-1]
    first = result[0]
    if first[0] <= last[1] - wrap:
        result[-1][1] = max(result[-1][1], first[1] + wrap)
        result.pop(0)
    return result