Restructure main function