working implementation of encode and decode