#936 rebased & expanded

This a rebase of @Gumnos 's PR 936 to current master status.

Also, last commit adds some additional guards. Feel free to  ask for a undo if you consider they aren't worth/correct.