Port changes from #402 to master.