updated encode function