Fix encode function