refactored to get rid of global vars
sx