Fixed some bugs in scope handling.