More diligent error checking. Patch by Julian Gilbey.