Revert "Revert "Fix for #1165 and #1200""

This reverts commit b9cfd8cb942c159d5c1c7b784c61ec1db43a32ff.