refactored. much fewer lines