The code below is modified from Patrik Ferrari's applet.