#!/usr/bin/env python

def rstrip_incomplete_UTF8(text):
	i = len(text) - 1
	if i < 0:
		return text

	# ASCII byte:       0xxxxxxx.
	# UTF-8 start byte: 11xxxxxx.
	# UTF-8 inner byte: 10xxxxxx.

	# make sure we are not standing on an inner byte.
	while i >= 0 and ord(text[i]) & 0xC0 == 0x80: # 10xxxxxx binary.
		i = i - 1

	if i >= 0 and ord(text[i]) & 0x80 == 0x80: # 11xxxxxx binary.
		i = i - 1

	return text[ : i + 1]		

def abbreviate(text, max_length):
	""" abbreviate the given text to maximal max_length bytes """
	text = text.strip()
	return rstrip_incomplete_UTF8(text[ : max_length])
