Further to the discussion on emacs-devel, here is an updated patch. -- Peter Oliver