I don't know about the math, but maybe some sample code will help?