slightly refactored. should get code review