Add #3463 commits from @ghost

Initial commit from changes made by @ghost
Should check `if res` before doing all this,