This should fix bug #22836. Changes are quite important but I added several tests to ensure I'm doing it right