Remove global variables

remove global variables by putting everything into a function