You are right on the $base64body.
And on the rest please do what you think is right. Mine was only a quick hack while you are a deity, looking at the quality of the produced code :-)

Thanks.