Thanks to @dmyerscoug for the report and original patch and to @alasdairnicol for the added tests. Backport of a020dd0a99da13d0f024d42c46f01d8f503e9d5e from master.