issue #667 with a few bug fixes for it