Integrate bug fixes from #803 and #807