scoping and globals fixes and tests