refactored, still seems to work