restructure main logic