Refactored main function.