Fix bugs reported under #20474 + a couple of additional bugs discovered in the course of work. Relevant unit tests added. Fixes #20474.