This seems to be awefully long to include inline. I think it is better to separate this to a function handling subdocument cases.