Based (loosely) on patch by Ner'zhul, DarkXuan, and darkshines@sakha.net. Fixes issue #3429. --HG-- branch : trunk