Move main logic into function