done refactoring, working version