working, refactored