This is an refinement of commit 47f96cae with improved logging and a similar fix to another place with similar logic bug 1880