Here's some code. Non-complete, of course.