Stole fred's code for BSON. #739