Pull encoding out to a separate function