messy code working with text encoding