Still more fallout from dac40105e6a36923076cc7e8a636c92dc2cca26c, plus a
few fixes for glaring problems [14739912]
Somebody PLEASE rewrite this whole function when the chaos subsides