Rebase and continue #1397

Continue work on #1397, merged patches from @wtfuzz and @hexwave. The original pull request is apparently dead.