Forward porting of #1128

Portif of #1128 by @kezabelle. Still some tests failing.
Fix #1120