Refactor some of the encoding detection