extracted the logic, added minimal tests