Harald, thanks for the bug report. This part of Emacs is a bit messy, but I hacked away at it and came up with the attached proposed patch. This patch touches some code for Microsoft platforms so I'm CC'ing this to Eli. I'm also CC'ing Bug#9488 as I think it fixes the rest of that bug too.