refactored to remove some nested ifs