This is a rebased version of the patches from https://bugzilla.gnome.org/show_bug.cgi?id=753415 + some cleanup