fix bug 2370
Fix to bug #2370
Cherry-picked from commit 82f8f3a546401ae33370655b3e832d3c055819ee
Also some minor cleaning up of other code.