fixed several bugs including encoding