Refactor to cleaner thinking and get rid of global