Tweaked to work in 1.8.7 (except the multi-byte character handling)