Major refactor to get rid of global variables