This post explains something very similar and probably you can use as a baseline for what you are trying to achieve.
Cheers!