fix issue #840, #864 and #1099