refactored encode, still not happy with result