Backported changes from master by Sevak