Among other things the function claims that it does not handle null fields in an encoding which is required by RFC 1510. I also think the function seems rather complex and seems to duplicate chunks of code a lot. I believe it could benefit from abstraction.