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.