re-writing the encoding with while loops. handle unicode encoding str values.