Cleanly apply #499

Credits to @Cosmius for this patch.

Fix #360
Fix #499
Fix #361
Merge pull request #592 from untitaker/master

Cleanly apply #499