Do a depth-first-search everywhere and replace SetInternalScope

Fixes #49