def write_pagination_headers(data, offset, limit, response, uripath,
    resource_name):
    """Add pagination headers to the bottle response.

    See docs in :func:`paginated`.
    """
    items = data.get('results') or data.get('data') or {}
    count = len(items)
    try:
        total = int(data['collection-count'])
    except (ValueError, TypeError, KeyError):
        total = None
    if total is None and offset == 0 and (limit is None or limit > len(items)):
        total = count
    response.set_header('Content-Range', '%s %d-%d/%s' % (resource_name,
        offset, offset + max(count - 1, 0), total if total is not None else
        '*'))
    partial = False
    if offset:
        partial = True
    elif total is None and count == limit:
        partial = True
    elif total > count:
        partial = True
    if partial:
        uripath = uripath.strip('/')
        response.status = 206
        if total is None or offset + limit < total - 1:
            nextfmt = '</%s?limit=%d&offset=%d>; rel="next"; title="Next page"'
            response.add_header('Link', nextfmt % (uripath, limit, offset +
                limit))
        if offset > 0 and offset - limit >= 0:
            prevfmt = (
                '</%s?limit=%d&offset=%d>; rel="previous"; title="Previous page"'
                )
            response.add_header('Link', prevfmt % (uripath, limit, offset -
                limit))
        if offset > 0:
            firstfmt = '</%s?limit=%d>; rel="first"; title="First page"'
            response.add_header('Link', firstfmt % (uripath, limit))
        if total is not None and limit and limit < total:
            lastfmt = '</%s?offset=%d>; rel="last"; title="Last page"'
            if limit and total % limit:
                last_offset = total - total % limit
            else:
                last_offset = total - limit
            response.add_header('Link', lastfmt % (uripath, last_offset))
