refactor and add tests, fix issue with redefinening globals