Based on a patch from @fealebenpae, with input from @SolaWing and @rth7680, and testing from @superdump.