The first working version

Some of the code is pretty clumsy in places and needs cleaning up. This
is the first cut at the problem.