Forward porting of #1128 by @kezabelle. Still some tests failing.