# Buggy code
def add_overlay(
    orig,
    area,
    coast_dir,
    color=(0, 0, 0),
    width=0.5,
    resolution=None,
    level_coast=1,
    level_borders=1,
    fill_value=None,
):
    """Add coastline and political borders to image, using *color* (tuple
    of integers between 0 and 255).
    Warning: Loses the masks !
    *resolution* is chosen automatically if None (default), otherwise it should be one of:
    +-----+-------------------------+---------+
    | 'f' | Full resolution         | 0.04 km |
    | 'h' | High resolution         | 0.2 km  |
    | 'i' | Intermediate resolution | 1.0 km  |
    | 'l' | Low resolution          | 5.0 km  |
    | 'c' | Crude resolution        | 25  km  |
    +-----+-------------------------+---------+
    """

    if area is None:
        raise ValueError("Area of image is None, can't add overlay.")

    from pycoast import ContourWriterAGG

    if isinstance(area, str):
        area = get_area_def(area)
    LOG.info("Add coastlines and political borders to image.")

    if resolution is None:
        x_resolution = (area.area_extent[2] - area.area_extent[0]) / area.x_size
        y_resolution = (area.area_extent[3] - area.area_extent[1]) / area.y_size
        res = min(x_resolution, y_resolution)

        if res > 25000:
            resolution = "c"
        elif res > 5000:
            resolution = "l"
        elif res > 1000:
            resolution = "i"
        elif res > 200:
            resolution = "h"
        else:
            resolution = "f"

        LOG.debug("Automagically choose resolution %s", resolution)

    img = orig.pil_image(fill_value=fill_value)
    cw_ = ContourWriterAGG(coast_dir)
    cw_.add_coastlines(
        img, area, outline=color, resolution=resolution, width=width, level=level_coast
    )
    cw_.add_borders(
        img,
        area,
        outline=color,
        resolution=resolution,
        width=width,
        level=level_borders,
    )

    arr = da.from_array(np.array(img) / 255.0, chunks=CHUNK_SIZE)

    orig.data = xr.DataArray(
        arr,
        dims=["y", "x", "bands"],
        coords={
            "y": orig.data.coords["y"],
            "x": orig.data.coords["x"],
            "bands": list(img.mode),
        },
        attrs=orig.data.attrs,
    )


# Traceback (ValueError)
[INFO: 2018-10-08 23:46:08 : satpy.writers] Add coastlines and political borders to image.
[DEBUG: 2018-10-08 23:46:08 : satpy.writers] Automagically choose resolution f
[DEBUG: 2018-10-08 23:46:09 : trollimage.xrimage] Interval: left=<xarray.DataArray 'reshape-59920bd5c4344e209a876883f95f2db3' (bands: 1)>
array([0.])
Coordinates:
* bands     (bands) <U1 'L'
quantile  float64 0.005, right=<xarray.DataArray 'reshape-59920bd5c4344e209a876883f95f2db3' (bands: 1)>
array([67.693016])
Coordinates:
* bands     (bands) <U1 'L'
quantile  float64 0.995
Traceback (most recent call last):
File "msg4-ernst_single_channel.py", line 93, in <module>
global_scene.save_dataset(composite,'./MSG4.png', overlay={'coast_dir': '/home/cpeters/software/', 'width':1, 'color':(200, 200, 200)})
File "/home/cpeters/anaconda2/envs/pytroll/lib/python3.6/site-packages/satpy-0+unknown-py3.6.egg/satpy/scene.py", line 1054, in save_dataset
**save_kwargs)
File "/home/cpeters/anaconda2/envs/pytroll/lib/python3.6/site-packages/satpy-0+unknown-py3.6.egg/satpy/writers/__init__.py", line 611, in save_dataset
decorate=decorate, fill_value=fill_value)
File "/home/cpeters/anaconda2/envs/pytroll/lib/python3.6/site-packages/satpy-0+unknown-py3.6.egg/satpy/writers/__init__.py", line 354, in get_enhanced_image
add_overlay(img, dataset.attrs['area'], fill_value=fill_value, **overlay)
File "/home/cpeters/anaconda2/envs/pytroll/lib/python3.6/site-packages/satpy-0+unknown-py3.6.egg/satpy/writers/__init__.py", line 230, in add_overlay
resolution=resolution, width=width, level=level_coast)
File "/home/cpeters/anaconda2/envs/pytroll/lib/python3.6/site-packages/pycoast/cw_agg.py", line 418, in add_coastlines
y_offset=y_offset)
File "/home/cpeters/anaconda2/envs/pytroll/lib/python3.6/site-packages/pycoast/cw_base.py", line 598, in _add_feature
x_offset=x_offset, y_offset=y_offset, **kwargs)
File "/home/cpeters/anaconda2/envs/pytroll/lib/python3.6/site-packages/pycoast/cw_base.py", line 510, in add_shapes
draw = self._get_canvas(image)
File "/home/cpeters/anaconda2/envs/pytroll/lib/python3.6/site-packages/pycoast/cw_agg.py", line 52, in _get_canvas
return aggdraw.Draw(image)
ValueError: bad mode

# Fixed code
def add_overlay(
    orig,
    area,
    coast_dir,
    color=(0, 0, 0),
    width=0.5,
    resolution=None,
    level_coast=1,
    level_borders=1,
    fill_value=None,
):
    """Add coastline and political borders to image.

    Uses ``color`` for feature colors where ``color`` is a 3-element tuple
    of integers between 0 and 255 representing (R, G, B).

    .. warning::

        This function currently loses the data mask (alpha band).

    ``resolution`` is chosen automatically if None (default), otherwise it should be one of:

    +-----+-------------------------+---------+
    | 'f' | Full resolution         | 0.04 km |
    | 'h' | High resolution         | 0.2 km  |
    | 'i' | Intermediate resolution | 1.0 km  |
    | 'l' | Low resolution          | 5.0 km  |
    | 'c' | Crude resolution        | 25  km  |
    +-----+-------------------------+---------+

    """

    if area is None:
        raise ValueError("Area of image is None, can't add overlay.")

    from pycoast import ContourWriterAGG

    if isinstance(area, str):
        area = get_area_def(area)
    LOG.info("Add coastlines and political borders to image.")

    if resolution is None:
        x_resolution = (area.area_extent[2] - area.area_extent[0]) / area.x_size
        y_resolution = (area.area_extent[3] - area.area_extent[1]) / area.y_size
        res = min(x_resolution, y_resolution)

        if res > 25000:
            resolution = "c"
        elif res > 5000:
            resolution = "l"
        elif res > 1000:
            resolution = "i"
        elif res > 200:
            resolution = "h"
        else:
            resolution = "f"

        LOG.debug("Automagically choose resolution %s", resolution)

    if hasattr(orig, "convert"):
        # image must be in RGB space to work with pycoast/pydecorate
        orig = orig.convert("RGBA" if orig.mode.endswith("A") else "RGB")
    elif not orig.mode.startswith("RGB"):
        raise RuntimeError(
            "'trollimage' 1.6+ required to support adding "
            "overlays/decorations to non-RGB data."
        )
    img = orig.pil_image(fill_value=fill_value)
    cw_ = ContourWriterAGG(coast_dir)
    cw_.add_coastlines(
        img, area, outline=color, resolution=resolution, width=width, level=level_coast
    )
    cw_.add_borders(
        img,
        area,
        outline=color,
        resolution=resolution,
        width=width,
        level=level_borders,
    )

    arr = da.from_array(np.array(img) / 255.0, chunks=CHUNK_SIZE)

    new_data = xr.DataArray(
        arr,
        dims=["y", "x", "bands"],
        coords={
            "y": orig.data.coords["y"],
            "x": orig.data.coords["x"],
            "bands": list(img.mode),
        },
        attrs=orig.data.attrs,
    )
    return XRImage(new_data)