fixed some scope issues, factored out some functions