select scoping and code generation fixes