I had to do something similar to this with custom objects. I think this should be close (but may not be exactly) ...
stackoverflow.com