Refactor running terminal function