Refactored some logic. Following Tealeaf solutions.