refactored for readability and to remove callback globals