Restructure logic to be more readable, per Bill's suggestion