Fixes gh-594

Fixes issue #594 and is faster than @cmastudios version by a longshot.