import math


def bound_longitude(lon, rad=False):
    """
    Return a value between (-180, 180], handling the wrap-around
    """
    if rad:
        lon = lon * 180 / math.pi

    # Keeps longitude in [0, 360) range
    lon = lon % 360
    lon[lon > 180] = lon[lon > 180] % 180 - 180

    if rad:
        lon = lon * math.pi / 180
    return lon