Is this mechanism perfect? Absolutely not, but it's a great start. For a more robust solution, read to the end.