Better implementation, works with all encodings