complete encode function