Improve behavior with error_on_undefined_vars enabled (v2)

This pull request is re-submission of changes from #3407. It is rebased against current devel branch and implements changes negotiated in #3407.

* First patch enables deeper detection of undefined variables with `error_on_undefined_vars` enabled.
* Second patch is optional and implements 4 tests to check functionality added by first patch.