Various bug fixes - thanks Andrew Cull