Refactoring the encode function