Thanks Mariusz Felisiak for tests and Matthijs Kooijman for investigation and initial patch. Backport of 241deed2590bcb1d8c45271d44c86eaedfb57119 from master