improved code handling external scopes