Fix bugs found by David Groves