refactored to make more reliable