refactored to simplify and modularize