Curious thing is that I had to do exactly the same thing for a recent project but the code might be protected as a work for hire creation.
The other curious thing is that the resulting code performed differently based on the setting for MAX DEGREES OF PARALLELISM until I made a change in the structure of the Transact SQL involved. Contact me for more info.