Scroll to the bottom of this page and look through the "Similar Threads" section. The top hit is a similar question, and is accompanied with code that you might find useful.
Type: Posts; User: copeg
Scroll to the bottom of this page and look through the "Similar Threads" section. The top hit is a similar question, and is accompanied with code that you might find useful.