This is my solution. Handles the basic cases very well, but gets overwhelmed by complicated ones.
http://pastie.caboo.se/private/mk82p5c00tqwhqmzigqbxw
-- 
Dominik Honnef