Click here to view my code. It is still not perfect. Comments, bug reports welcome.
Thanks to V for speeding this up.
Updated : Suggestions made by Dante (see comments) have been incorporated and the new code has been uploaded.