Fixed a memory leak in encoder and cleand up code.