Refactored to get rid of global variables