the code is a bit crufty, but this should fix issue #687