Refactored to dry up main code