Base code from http://www.cs.bell-labs.com/cm/cs/pearls/code.html