Implement encode function