From upstream 6a238e9cb4acda222898dd4b597cf20581b401f6 This replaces a slightly different fix we had in ScummVM. But this new code works better and fixes bug #12949