Main function refactoring