Based on this example from Giles Thomas.