Fix #1040 + tests

Cherry picked from commits:
  * cda9f28e76521eed618300f5cdf6399a09b00b8e
  * f270a9673c4f64d2ecf5ae8aa31a66269180b643
  * d43feb268b65dbae5067ffc208b63b9750489c5a
  * 983857ede086e70c1597fdf021cf1643d769a18c