Fix bugs in encoder