scope changes

changed variable scope and moved some code around