pulled out the callback handler to a seperate function to reduce duplication
added support for encoding unions. Fun right?