Refactor terminal and function code out of tree