Solution to problem 45.

Probably more code here than is needed.